/**
 *====================================================
 * 文件名称: FinanceBulkstockPledgeActionApiImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年10月23日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.project.action.v1;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.bulkstock.entity.BulkstockInfoEntity;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.common.util.LongUtils;
import com.yuexunit.finance.context.FinanceBaseAction;
import com.yuexunit.finance.context.FinanceConstant;
import com.yuexunit.finance.context.FinanceLetterBlockingQueue;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.project.action.v1.dto.BulkstockPledgeCastor;
import com.yuexunit.finance.project.action.v1.dto.ExchangeInventoryCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceLoanCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceProcessCastor;
import com.yuexunit.finance.project.action.v1.dto.TallyingDeliveryCastor;
import com.yuexunit.finance.project.action.v1.model.AppointPickupParams;
import com.yuexunit.finance.project.action.v1.model.PickupApplication;
import com.yuexunit.finance.project.action.v1.model.PickupAuditInfo;
import com.yuexunit.finance.project.action.v1.model.input.NormalPickupParams;
import com.yuexunit.finance.project.action.v1.model.output.ExchangeContainerBulkstock;
import com.yuexunit.finance.project.action.v1.model.output.ExchangeContainerInventory;
import com.yuexunit.finance.project.action.v1.model.output.ExchangeInventoryInfo;
import com.yuexunit.finance.project.action.v1.model.output.HandleSuitcaseResult;
import com.yuexunit.finance.project.action.v1.model.output.PickupApplicationDetail;
import com.yuexunit.finance.project.action.v1.model.output.PickupApplicationLineInfo;
import com.yuexunit.finance.project.action.v1.model.output.PickupDelayApplicationDetail;
import com.yuexunit.finance.project.action.v1.model.output.PickupDelayApplicationLineInfo;
import com.yuexunit.finance.project.entity.ContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryHistoryEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryTallyEntity;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceAuditLogEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.FinanceCompleteResultEntity;
import com.yuexunit.finance.project.entity.FinanceContainerEntity;
import com.yuexunit.finance.project.entity.FinanceContainerLogEntity;
import com.yuexunit.finance.project.entity.FinanceCreditReplenishContainerEntity;
import com.yuexunit.finance.project.entity.FinanceMoneyStatementDetailsEntity;
import com.yuexunit.finance.project.entity.FinanceMoneyStatementEntity;
import com.yuexunit.finance.project.entity.FinanceProcessDetailEntity;
import com.yuexunit.finance.project.entity.FinanceProcessEntity;
import com.yuexunit.finance.project.entity.PickupApplicationEntity;
import com.yuexunit.finance.project.entity.PickupBulkstockEntity;
import com.yuexunit.finance.project.entity.PickupDelayApplicationEntity;
import com.yuexunit.finance.project.entity.PickupExchangeContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.PickupExchangeContainerEntity;
import com.yuexunit.finance.project.entity.PickupExchangeEntity;
import com.yuexunit.finance.project.entity.PickupInventoryBulstockEntity;
import com.yuexunit.finance.project.entity.PickupInventoryEntity;
import com.yuexunit.finance.project.entity.QuarterSettlementContainerEntity;
import com.yuexunit.finance.project.entity.QuarterSettlementEntity;
import com.yuexunit.finance.project.entity.lexicon.AbnormalResultEnum;
import com.yuexunit.finance.project.entity.lexicon.AbnormalStateEnum;
import com.yuexunit.finance.project.entity.lexicon.AbnormalTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.ApiFinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ApiTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.ApplicationSimpleStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ApplicationStateEnum;
import com.yuexunit.finance.project.entity.lexicon.BadassetsStateEnum;
import com.yuexunit.finance.project.entity.lexicon.BulkstockSourceEnum;
import com.yuexunit.finance.project.entity.lexicon.ExchangeStatusEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.OperatorRoleEnum;
import com.yuexunit.finance.project.entity.lexicon.PickupMethodEnum;
import com.yuexunit.finance.project.entity.lexicon.PickupModelEnum;
import com.yuexunit.finance.project.entity.lexicon.PickupTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.ProductTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.ReplenishStateEnum;
import com.yuexunit.finance.project.entity.lexicon.StatementStateEnum;
import com.yuexunit.finance.project.entity.lexicon.SupervisionStateEnum;
import com.yuexunit.finance.project.service.BailReturnService;
import com.yuexunit.finance.project.service.FinanceAuditLogService;
import com.yuexunit.finance.project.service.FinanceMoneyStatementDetailsService;
import com.yuexunit.finance.project.service.FinanceProductService;
import com.yuexunit.finance.project.service.PickupExchangeContainerBulkstockService;
import com.yuexunit.finance.project.service.PickupExchangeContainerService;
import com.yuexunit.finance.project.service.PickupExchangeService;
import com.yuexunit.finance.project.service.PickupInventoryService;
import com.yuexunit.finance.system.action.v1.dto.SendLetterMessage;
import com.yuexunit.finance.system.service.SystemParamService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.permission.action.PermissionActionsApi;
import com.yuexunit.permission.action.dto.RoleListDto;
import com.yuexunit.persist.PersistUtil;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;

/**
 * @ClassName: FinanceBulkstockPledgeActionApiImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年10月23日 上午6:48:38
 */
@Implements(FinanceBulkstockPledgeActionApi.class)
public class FinanceBulkstockPledgeActionApiImpl extends FinanceBaseAction implements FinanceBulkstockPledgeActionApi {
	
	public static Logger logger = LoggerFactory.getLogger(FinanceBulkstockPledgeActionApiImpl.class);
	
	protected PickupExchangeService pickupExchangeService = ComponentFactory.loadClass(PickupExchangeService.class);

	protected PickupExchangeContainerService pickupExchangeContainerService = ComponentFactory.loadClass(PickupExchangeContainerService.class);

	protected PickupExchangeContainerBulkstockService pickupExchangeContainerBulkstockService = ComponentFactory.loadClass(PickupExchangeContainerBulkstockService.class);

	protected BailReturnService bailReturnService = ComponentFactory.loadClass(BailReturnService.class);
	
	protected FinanceMoneyStatementDetailsService financeMoneyStatementDetailsService = ComponentFactory.loadClass(FinanceMoneyStatementDetailsService.class);
	
	protected FinanceProductService financeProductService = ComponentFactory.loadClass(FinanceProductService.class);
	
	protected FinanceAuditLogService financeAuditLogService = ComponentFactory.loadClass(FinanceAuditLogService.class);
	
	protected PickupInventoryService pickupInventoryService = ComponentFactory.loadClass(PickupInventoryService.class);
	
	protected SystemParamService systemParamService = ComponentFactory.loadClass(SystemParamService.class);
	
	protected FinanceApplicationActionApi financeApplicationActionApi = ComponentFactory.loadClass(FinanceApplicationActionApi.class);
	
	private String tmp = "客户(%s)融资(%s)目前处于提货审批环节对应的(%s)节点，请及时审批！";

	private QuarterSettlementContainerEntity matchQuarterSettlementContainer(QuarterSettlementEntity settlement, ContainerInventoryEntity container) {
		if (settlement == null) {
			return null;
		}
		for (QuarterSettlementContainerEntity a : settlement.getContainers()) {
			if (a.getInventoryId().equals(container.getInventoryId())) {
				return a;
			}
		}
		return null;
	}

	// 现金提箱
	private void cashContainerPickup(QuarterSettlementEntity settlement, FinanceApplicationEntity finance, PickupApplication params, PickupApplicationEntity pickup, List<ContainerInventoryEntity> inventories) {
		if (settlement != null) {
			pickup.setBulkstockInterest(settlement.getInterestAmount().add(settlement.getPunishAmount()));
		}
		pickup.setFinanceValuation(BigDecimal.ZERO);
		pickup.setExpense(BigDecimal.ZERO); // 暂不处理其他费用
		for (ContainerInventoryEntity cie : inventories) {
			cie.setPickupId(pickup.getPickupId());
			cie.setPickupModel(PickupModelEnum.USER_ASSIGN);
			containerInventoryService.renovateContainerInventory(cie);

			QuarterSettlementContainerEntity sc = matchQuarterSettlementContainer(settlement, cie);
			PickupInventoryEntity pickupInventory = new PickupInventoryEntity();
			pickupInventory.setPickupId(pickup.getPickupId());
			pickupInventory.setInventoryId(cie.getInventoryId());
			pickupInventory.setPickupInventoryId(cie.getInventoryId());
			if (sc != null) {
				pickupInventory.setInterest(sc.getInterestAmount().add(sc.getPunishAmount()));
			} else {
				pickupInventory.setInterest(BigDecimal.ZERO);
			}
			pickupInventoryService.createPickupInventory(pickupInventory);

			List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockList(cie.getInventoryId());
			for (ContainerBulkstockEntity cbe : cbes) {
				PickupInventoryBulstockEntity pibe = new PickupInventoryBulstockEntity();
				pibe.setContainerBulkstockId(cbe.getContainerBulkstockId());
				pibe.setPickupId(pickupInventory.getPickupId());
				pibe.setInventoryId(cbe.getInventoryId());
				pibe.setPickupInventoryId(pickupInventory.getPickupInventoryId());
				pickupInventoryBulstockService.createPickupInventoryBulstock(pibe);

				pickup.setFinanceValuation(pickup.getFinanceValuation().add(cbe.getValuationFinanceAmount()));
			}
			pickup.setFinanceValuation(pickup.getFinanceValuation().add(cie.getAdjustment()));
		}
		// 生成提货单货物信息
		Collection<PickupBulkstockEntity> bulkstockEntities = BulkstockPledgeCastor.fromPickupInventory(inventories);
		for (PickupBulkstockEntity pce : bulkstockEntities) {
			pickupBulkstockService.createPickupBulkstock(pce);
		}
	}

	// 换货提货
	private void exchangeBulkstockPickup(FinanceApplicationEntity finance, NormalPickupParams params, PickupApplicationEntity pickup, List<ContainerInventoryEntity> inventories) {
		pickup.setBulkstockInterest(BigDecimal.ZERO);
		pickup.setExpense(BigDecimal.ZERO); // 暂不处理其他费用
		pickup.setEstimateAmount(pickup.getFinanceValuation());
		// 生成换货信息
		for (int i = 0; i < params.getBulkstockInfoId().length; i++) {
			Long bulkstockInfoId = params.getBulkstockInfoId()[i];
			BulkstockInfoEntity bulkstockInfo = bulkstockInfoService.inquireBulkstockInfo(bulkstockInfoId);
			PickupExchangeEntity exchange = new PickupExchangeEntity();
			exchange.setPickupId(pickup.getPickupId());
			exchange.setBulkstockCategoryId(bulkstockInfo.getBulkstockCategoryId());
			exchange.setBulkstockInfoId(bulkstockInfo.getBulkstockInfoId());
			exchange.setBulkstockName(bulkstockInfo.getBulkstockName());
			exchange.setSpecification(bulkstockInfo.getSpecificationName());
			exchange.setBulkstockNumber(bulkstockInfo.getBulkstockNumber());
			exchange.setMeasurement(bulkstockInfo.getMeasurement());
			exchange.setBulkstockPrice(params.getBulkstockPrice()[i]);
			exchange.setManufacturer(params.getManufacturer()[i]);
			exchange.setOriginPlace(params.getOriginPlace()[i]);
			exchange.setQuantity(params.getWeight()[i]);
			exchange.setWeight(params.getWeight()[i]);
			exchange.setVolume(BigDecimal.ZERO);
			exchange.setValuationQuantity(params.getWeight()[i]);
			exchange.setUnit("批");
			exchange.setValuationDate(DateUtil.todayInt());
			pickupExchangeService.createPickupExchange(exchange);
		}
	}

	// 换箱提货
	private void exchangeContainerPickup(FinanceApplicationEntity finance, NormalPickupParams params, PickupApplicationEntity pickup, List<ContainerInventoryEntity> inventories) {
		if (params.getCaseNumber().length <= 0) {
			throw new BusinessException("换箱箱号不允许为空");
		}
		Set<String> tempValidateCaseNumbers = new HashSet<String>();
		for (int i = 0; i < params.getCaseNumber().length; i++) {
			String caseNumber = params.getCaseNumber()[i].trim();
			if (tempValidateCaseNumbers.contains(caseNumber)) {
				throw new BusinessException("换箱箱号不允许重复");
			}
			tempValidateCaseNumbers.add(caseNumber);
		}
		pickup.setBulkstockInterest(BigDecimal.ZERO);
		pickup.setExpense(BigDecimal.ZERO); // 暂不处理其他费用
		pickup.setEstimateAmount(pickup.getFinanceValuation());
		Map<Long, PickupExchangeEntity> exchanges = new HashMap<>();
		// 生成换箱信息
		for (int i = 0; i < params.getCaseNumber().length; i++) {
			String caseNumber = params.getCaseNumber()[i].trim();
			String waybillNumber = params.getWaybillNumber()[i].trim();
			List<ContainerInventoryEntity> exists = containerInventoryService.inquireContainerInventory(null, waybillNumber, caseNumber);
			if (!exists.isEmpty()) {
				throw new BusinessException("申请的换箱箱号[" + caseNumber + "]已经存在");
			}
			
//			HandleSuitcaseResult result = financeApplicationActionApi.containerTaken(waybillNumber, caseNumber);
//			if (result.getResult() == false) {
//				throw new BusinessException(result.getMessage());
//			}
			
			PickupExchangeContainerEntity container = new PickupExchangeContainerEntity();
			container.setPickupId(pickup.getPickupId());
			container.setCaseNumber(caseNumber);
			// container.setCaseSize(params.getCaseSize()[i]);
			// container.setFacingSlip(params.getFacingSlip()[i]);
			container.setWaybillNumber(waybillNumber);
			pickupExchangeContainerService.createPickupExchangeContainer(container);

			Long bulkstockInfoId = params.getBulkstockInfoId()[i];
			BulkstockInfoEntity bulkstockInfo = bulkstockInfoService.inquireBulkstockInfo(bulkstockInfoId);
			PickupExchangeContainerBulkstockEntity bulkstock = new PickupExchangeContainerBulkstockEntity();
			bulkstock.setContainerId(container.getContainerId());
			bulkstock.setBulkstockCategoryId(bulkstockInfo.getBulkstockCategoryId());
			bulkstock.setBulkstockInfoId(bulkstockInfo.getBulkstockInfoId());
			bulkstock.setBulkstockName(bulkstockInfo.getBulkstockName());
			bulkstock.setMeasurement(bulkstockInfo.getMeasurement());
			bulkstock.setSpecification(bulkstockInfo.getSpecificationName());
			// bulkstock.setTrayNumber(params.getTrayNumber()[i]);
			bulkstock.setQuantity(params.getWeight()[i] != null ? params.getWeight()[i] : null);
			bulkstock.setValuationQuantity(params.getWeight()[i]);
			bulkstock.setVolume(BigDecimal.ZERO);
			bulkstock.setWeight(params.getWeight()[i]);
			bulkstock.setUnit("批");
			pickupExchangeContainerBulkstockService.createPickupExchangeContainerBulkstock(bulkstock);

			PickupExchangeEntity exchange = exchanges.get(bulkstock.getBulkstockInfoId());
			if (exchange == null) {
				exchange = new PickupExchangeEntity();
				exchange.setPickupId(pickup.getPickupId());
				exchange.setBulkstockCategoryId(bulkstockInfo.getBulkstockCategoryId());
				exchange.setBulkstockInfoId(bulkstockInfo.getBulkstockInfoId());
				exchange.setBulkstockName(bulkstockInfo.getBulkstockName());
				exchange.setSpecification(bulkstockInfo.getSpecificationName());
				exchange.setBulkstockNumber(bulkstockInfo.getBulkstockNumber());
				exchange.setMeasurement(bulkstockInfo.getMeasurement());
				exchange.setBulkstockPrice(BigDecimal.ZERO);
				exchange.setManufacturer(null);
				exchange.setOriginPlace(null);
				exchange.setVolume(BigDecimal.ZERO);
				exchange.setUnit("批");
				exchange.setValuationDate(DateUtil.todayInt());
				exchange.setQuantity(BigDecimal.ZERO);
				exchange.setWeight(BigDecimal.ZERO);
				exchange.setValuationQuantity(BigDecimal.ZERO);
				exchanges.put(bulkstock.getBulkstockInfoId(), exchange);
			}
			exchange.setWeight(exchange.getWeight().add(bulkstock.getWeight()));
			exchange.setQuantity(exchange.getQuantity().add(bulkstock.getQuantity()));
			exchange.setValuationQuantity(exchange.getWeight());
		}
		// 生成换货信息
		for (Entry<Long, PickupExchangeEntity> entry : exchanges.entrySet()) {
			pickupExchangeService.createPickupExchange(entry.getValue());
		}
	}

	private void completePickupBulkstockInventory(FinanceApplicationEntity finance, PickupApplication params, PickupApplicationEntity pickup) {
		Long[] inventoryIds = params.getInventoryIds();
		List<ContainerInventoryEntity> inventories = containerInventoryService.inquireContainerInventoryList(inventoryIds);
//		FinanceProductEntity product = financeProductService.inquireFinanceProduct(finance.getProductId());
		Date valueDate = inventories.get(0).getValueDate();
		Date settlementDate = inventories.get(0).getSettlementDate();
		for (ContainerInventoryEntity cie : inventories) {
			if (cie.getPickupId() != null && !cie.getPickupId().equals(pickup.getPickupId())) {
				throw new BusinessException("箱号" + cie.getCaseNumber() + "已经被申请提取");
			}
			if (PickupMethodEnum.EXCHANGE_BULKSTOCK == pickup.getPickupMethod()) {
				if (!cie.getSettlementDate().equals(settlementDate) || !cie.getValueDate().equals(valueDate)) {
					throw new BusinessException("箱号" + cie.getCaseNumber() + "与其他箱的结息日期不一致,无法一起提交换货申请");
				}
			} else if (PickupMethodEnum.EXCHANGE_CONTAINER == pickup.getPickupMethod()) {
				if (!cie.getSettlementDate().equals(settlementDate) || !cie.getValueDate().equals(valueDate)) {
					throw new BusinessException("箱号" + cie.getCaseNumber() + "与其他箱的结息日期不一致,无法一起提交换箱申请");
				}
			}
		}
		QuarterSettlementEntity settlement = null;
		if (PickupMethodEnum.CASH_DELIVERY == pickup.getPickupMethod()) {
//			settlement = FinanceLoanCastor.fromInterestSettlement(finance, inventories, product.getQuantitySettlement(), pickup, false);
		}
		cashContainerPickup(settlement, finance, params, pickup, inventories);
		if (PickupMethodEnum.EXCHANGE_BULKSTOCK == pickup.getPickupMethod() && params instanceof NormalPickupParams) {
			exchangeBulkstockPickup(finance, (NormalPickupParams) params, pickup, inventories);
		} else if (PickupMethodEnum.EXCHANGE_CONTAINER == pickup.getPickupMethod() && params instanceof NormalPickupParams) {
			exchangeContainerPickup(finance, (NormalPickupParams) params, pickup, inventories);
		}
	}

	private void createPickupApplicationFinanceProcess(PickupApplicationEntity pickupEntity) {
		// 项目动态
		FinanceProcessEntity processEntity = FinanceProcessCastor.fromFinancePickupApplicationProcess(pickupEntity);
		financeProcessService.createFinanceProcess(processEntity);
		if (!LongUtils.isPrimaryKey(processEntity.getParentProcess().getProcessId())) {
			financeProcessService.createFinanceProcess(processEntity.getParentProcess());
		} else {
			financeProcessService.renovateFinanceProcess(processEntity.getParentProcess());
		}
		FinanceProcessDetailEntity currentDetail = processEntity.getCurrentDetail();
		currentDetail.setProcessId(processEntity.getProcessId());
		financeProcessDetailService.createFinanceProcessDetail(processEntity.getCurrentDetail());
	}

	private void consentPickupApplication(PickupApplicationEntity persist) {
		// 项目动态
		FinanceProcessEntity processEntity = FinanceProcessCastor.fromFinancePickupAuditProcess(persist, true);
		financeProcessService.renovateFinanceProcess(processEntity);
		financeProcessDetailService.createFinanceProcessDetail(processEntity.getCurrentDetail());
	}

	private void opposePickupApplication(PickupApplicationEntity persist) {
		List<ContainerInventoryEntity> inventoryList = containerInventoryService.inquirePickupContainerInventoryList(persist.getPickupId());
		for (ContainerInventoryEntity cie : inventoryList) {
			cie.setPickupId(null);
			cie.setPickupModel(PickupModelEnum.UNKNOWN);
			containerInventoryService.renovateContainerInventory(cie);
		}

		// 项目动态
		FinanceProcessEntity processEntity = FinanceProcessCastor.fromFinancePickupAuditProcess(persist, false);
		financeProcessService.renovateFinanceProcess(processEntity);
		financeProcessDetailService.createFinanceProcessDetail(processEntity.getCurrentDetail());
	}

	private void validatePickupApplication(FinanceApplicationEntity finance) {
		if (finance.getBail().compareTo(BigDecimal.ZERO) > 0) {
			String[] statementSource = new String[] { "FINANCE_AUDIT", "BAIL_ADDITION", "QUARTER_SETTLEMENT" };
			FinanceMoneyStatementEntity statement = financeMoneyStatementService.inquireFinanceMoneyStatementDetail(statementSource, finance.getFinanceId());
			if (statement != null && !statement.getReceiptVerifiState()) {
				throw new BusinessException("保证金/利息未核销,不允许提货");
			}
		}
	}

	private void processConsentNormalPickupApplication(PickupApplicationEntity pickup, Long[] exchangeIds, BigDecimal[] evaluatePrices, BigDecimal[] lowestPrices, BigDecimal[] highestPrices) {
		if (PickupMethodEnum.CASH_DELIVERY == pickup.getPickupMethod()) {
			return;
		}
		BigDecimal financeAmount = pickup.getFinanceValuation();
		BigDecimal evaluateAmount = BigDecimal.ZERO;
		List<PickupExchangeEntity> exchanges = pickupExchangeService.inquirePickupExchangeList(pickup);
		// 计算估值总额(用来计算融资单价)
		for (PickupExchangeEntity exchange : exchanges) {
			if(exchangeIds!=null){
				for (int i = 0; i < exchangeIds.length; i++) {
					if (exchange.getExchangeId().equals(exchangeIds[i])) {
						evaluateAmount = evaluateAmount.add(evaluatePrices[i].multiply(exchange.getValuationQuantity()));
						break;
					}
				}
			}
		}
		Map<Long, FinanceBulkstockEntity> financeBulkstocks = new HashMap<>();
		for (PickupExchangeEntity exchange : exchanges) {
			BigDecimal evaluatePrice = null;
			BigDecimal lowestPrice = null;
			BigDecimal highestPrice = null;
			if(exchangeIds!=null){
				for (int i = 0; i < exchangeIds.length; i++) {
					if (exchange.getExchangeId().equals(exchangeIds[i])) {
						evaluatePrice = evaluatePrices[i];
						lowestPrice = lowestPrices[i];
						highestPrice = highestPrices[i];
						break;
					}
				}
			}
			if (evaluatePrice == null) {
				throw new BusinessException("未匹配到 换货/换箱 提货货物信息[" + exchange.getBulkstockName() + "");
			}
			if (evaluatePrice.compareTo(BigDecimal.ZERO) < 1) {
				throw new BusinessException("换货/换箱 提货货物信息[" + exchange.getBulkstockName() + "]评估价格不允许小于0");
			}
			exchange.setEvaluatePrice(evaluatePrice);
			exchange.setLowestPrice(lowestPrice);
			exchange.setHighestPrice(highestPrice);

			if (PickupMethodEnum.EXCHANGE_BULKSTOCK == pickup.getPickupMethod()) { // 换货
				// 合并至融资货物中
				FinanceBulkstockEntity bulkstock = new FinanceBulkstockEntity();
				BeanUtils.copyProperties(exchange, bulkstock);
				bulkstock.setBulkstockSource(BulkstockSourceEnum.PICKUP);
				bulkstock.setExchangePickupId(pickup.getPickupId());
				bulkstock.setFinanceId(pickup.getFinanceId());
				bulkstock.setCargoMark(null);
				bulkstock.setColdStorage(Boolean.FALSE);
				bulkstock.setDangerous(Boolean.FALSE);
				bulkstock.setPublicity(Boolean.FALSE);
				bulkstock.setFinancePrice(bulkstock.getEvaluatePrice().multiply(financeAmount).divide(evaluateAmount, 2, BigDecimal.ROUND_HALF_UP));

				bulkstock.setAbnormal(BigDecimal.ZERO);
				bulkstock.setPickup(BigDecimal.ZERO);
				bulkstock.setHarbor(BigDecimal.ZERO);
				// 换货需要通知收货流程
				bulkstock.setRecieve(BigDecimal.ZERO);
				bulkstock.setSupervision(BigDecimal.ZERO);
				bulkstock.setIncustody(BigDecimal.ZERO);
				financeBulkstockService.createFinanceBulkstockEntity(bulkstock);
				exchange.setBulkstockId(bulkstock.getBulkstockId());
				pickupExchangeService.renovatePickupExchange(exchange);
				financeBulkstocks.put(bulkstock.getBulkstockInfoId(), bulkstock);
			}
		}
	}

	private void protocolNormalPickupApplicationExchangeContainer(PickupApplicationEntity pickup) {
		if (PickupMethodEnum.EXCHANGE_BULKSTOCK == pickup.getPickupMethod()) { // 换货
			return;
		}
		BigDecimal financeAmount = pickup.getFinanceValuation();//货物金额
		BigDecimal evaluateAmount = BigDecimal.ZERO;//估值总额
		Map<Long, FinanceBulkstockEntity> financeBulkstocks = new HashMap<>();//融资货物Map
		List<PickupExchangeEntity> exchanges = pickupExchangeService.inquirePickupExchangeList(pickup);//融资换箱 货物信息
		for (PickupExchangeEntity exchange : exchanges) {
			evaluateAmount = evaluateAmount.add(exchange.getEvaluatePrice().multiply(exchange.getValuationQuantity()));
		}
		for (PickupExchangeEntity exchange : exchanges) {
			// 合并至融资货物中
			FinanceBulkstockEntity bulkstock = new FinanceBulkstockEntity();
			BeanUtils.copyProperties(exchange, bulkstock);
			bulkstock.setBulkstockSource(BulkstockSourceEnum.PICKUP);
			bulkstock.setExchangePickupId(pickup.getPickupId());
			bulkstock.setFinanceId(pickup.getFinanceId());
			bulkstock.setCargoMark(null);
			bulkstock.setColdStorage(Boolean.FALSE);
			bulkstock.setDangerous(Boolean.FALSE);
			bulkstock.setPublicity(Boolean.FALSE);

			bulkstock.setFinancePrice(bulkstock.getEvaluatePrice().multiply(financeAmount).divide(evaluateAmount, 2, BigDecimal.ROUND_HALF_UP));

			bulkstock.setAbnormal(BigDecimal.ZERO);
			bulkstock.setPickup(BigDecimal.ZERO);
			bulkstock.setHarbor(BigDecimal.ZERO);
			bulkstock.setRecieve(exchange.getQuantity());
			bulkstock.setSupervision(exchange.getQuantity());
			bulkstock.setIncustody(exchange.getQuantity());
			financeBulkstockService.createFinanceBulkstockEntity(bulkstock);
			exchange.setBulkstockId(bulkstock.getBulkstockId());
			pickupExchangeService.renovatePickupExchange(exchange);
			financeBulkstocks.put(bulkstock.getBulkstockInfoId(), bulkstock);
		}

		// 换箱操作-生成换箱信息(一箱一货)
		ContainerInventoryEntity ci = containerInventoryService.inquirePickupContainerInventoryList(pickup.getPickupId()).get(0); // 取出换箱信息中的其中一个,用来初始化计息信息
		List<PickupExchangeContainerEntity> containers = pickupExchangeContainerService.inquirePickupExchangeContainerList(pickup.getPickupId());
		Long[] containerIds = new Long[containers.size()];
		for (int i = 0; i < containers.size(); i++) {
			containerIds[i] = containers.get(i).getContainerId();
		}
		List<PickupExchangeContainerBulkstockEntity> list = pickupExchangeContainerBulkstockService.inquirePickupExchangeContainerBulkstockList(containerIds);
		// 固定一箱一货
		Map<Long, PickupExchangeContainerBulkstockEntity> bulkstocks = new HashMap<>();
		for (PickupExchangeContainerBulkstockEntity pcbe : list) {
			bulkstocks.put(pcbe.getContainerId(), pcbe);
		}

		FinanceApplicationActionApiImpl faaai = new FinanceApplicationActionApiImpl();
		for (int i = 0; i < containers.size(); i++) {
			PickupExchangeContainerEntity pce = containers.get(i);
			List<ContainerInventoryHistoryEntity> his = containerInventoryHistoryService.inquireEmptyFinanceContainerInventory(pce.getWaybillNumber(), pce.getCaseNumber());
			ContainerInventoryEntity cie = new ContainerInventoryEntity();
			cie.setContainerSource(BulkstockSourceEnum.PICKUP);
			cie.setExchangePickupId(pickup.getPickupId());
			cie.setReplenishCreditId(null);
			cie.setEnterpriseId(pickup.getEnterpriseId());
			cie.setEnterpriseName(pickup.getEnterpriseName());
			cie.setFinanceId(pickup.getFinanceId());
			cie.setFinanceNumber(pickup.getFinanceNumber());
			cie.setRecieveNoticeId(null);
			cie.setTallyingId(null);
			cie.setTallyingCompanyId(null);
			cie.setConfirmationId(null);
			cie.setLoanNoticeId(pickup.getLoanNoticeId());
			cie.setTransportNoticeId(null);
			cie.setTransportCompanyId(null);
			cie.setPickupId(null);
			cie.setDeliveryCompanyId(null);
			cie.setDeliveryId(null);
			cie.setDeliveryNoticeId(null);
			cie.setPickupModel(PickupModelEnum.UNKNOWN);
			cie.setWaybillNumber(pce.getWaybillNumber());
			cie.setCaseNumber(pce.getCaseNumber());
			cie.setCaseSize(pce.getCaseSize());
			cie.setModel(cie.getCaseSize().replaceAll("[^0-9]", ""));
			cie.setDimension(cie.getCaseSize().replaceAll("[0-9]", ""));
			cie.setFacingSlip(pce.getFacingSlip());
			cie.setFacingSlipNext(null);
			cie.setAbnormal(Boolean.TRUE);
			cie.setAbnormalState(AbnormalStateEnum.UNKNOWN);
			cie.setAbnormalType(AbnormalTypeEnum.UNKNOWN);
			cie.setLatestAbnormalResult(AbnormalResultEnum.UNKNOWN);
			cie.setTallyingState(Boolean.TRUE);
			cie.setTallyDateTime(DateUtils.now());
			cie.setHarborState(Boolean.FALSE);
			cie.setHarborDateTime(null);
			cie.setShipsName(null);
			cie.setVoyageNumber(null);
			cie.setSignState(Boolean.FALSE);
			cie.setSignDateTime(null);
			cie.setSupervisionState(SupervisionStateEnum.ALREADY_REPORT); // 进入已上报->收货确认->监管确认
			cie.setRedeemState(Boolean.FALSE);
			cie.setDetainedState(Boolean.FALSE);
			cie.setBadassetsState(BadassetsStateEnum.UNKNOWN);
			cie.setValueDate(ci.getValueDate());
			cie.setSettlementDate(ci.getSettlementDate());
			cie.setPickupableDate(ci.getPickupableDate());
			cie.setPunishDate(ci.getPunishDate());
			cie.setDistrainDate(ci.getDistrainDate());
			cie.setHandleDate(ci.getHandleDate());
			cie.setAdjustment(BigDecimal.ZERO);
			cie.setRecieveNoticeId(ci.getRecieveNoticeId());
			if (his != null && his.size() > 0) {
				cie.setLogisticsCompanyInfoId(his.get(0).getLogisticsCompanyInfoId());
			}

			PickupExchangeContainerBulkstockEntity pcbe = bulkstocks.get(pce.getContainerId());
			FinanceBulkstockEntity financeBulkstock = financeBulkstocks.get(pcbe.getBulkstockInfoId());
			containerInventoryService.createContainerInventory(cie);
			ContainerInventoryTallyEntity cite = new ContainerInventoryTallyEntity();
			cite.setInventoryId(cie.getInventoryId());
			cite.setTallyAddress(pce.getTallyAddress());
			cite.setTallyLongitude(pce.getTallyLongitude());
			cite.setTallyLatitude(pce.getTallyLatitude());
			cite.setTallyPreFile(pce.getTallyPreFile());
			cite.setTallySuffixFile(pce.getTallySuffixFile());
			cite.setTallyRemark(pce.getTallyRemark());
			cite.setTallyExAbnormalState(pce.getTallyExAbnormalState());
			cite.setTallyExAddress(pce.getTallyExAddress());
			cite.setTallyExLongitude(pce.getTallyExLongitude());
			cite.setTallyExLatitude(pce.getTallyExLatitude());
			cite.setTallyExRemark(pce.getTallyExRemark());
			cite.setTallyExAbnormalFile(pce.getTallyExAbnormalFile());
			containerInventoryTallyService.createContainerInventoryTally(cite);

			ContainerBulkstockEntity cbe = new ContainerBulkstockEntity();
			cbe.setTallyingId(null);
			cbe.setTransportNoticeId(null);
			cbe.setInventoryId(cie.getInventoryId());
			cbe.setFinanceId(pickup.getFinanceId());
			cbe.setBulkstockId(financeBulkstock.getBulkstockId());
			cbe.setBulkstockCategoryId(pcbe.getBulkstockCategoryId());
			cbe.setBulkstockInfoId(pcbe.getBulkstockInfoId());
			cbe.setBulkstockName(pcbe.getBulkstockName());
			cbe.setSpecification(pcbe.getSpecification());
			cbe.setUnit(pcbe.getUnit());
			cbe.setPlannedQuantity(pcbe.getQuantity());
			cbe.setPlannedVolume(pcbe.getVolume());
			cbe.setPlannedWeight(pcbe.getWeight());
			cbe.setQuantity(pcbe.getTallyQuantity());
			cbe.setVolume(pcbe.getTallyVolume());
			cbe.setWeight(pcbe.getTallyWeight());
			cbe.setMeasurement(pcbe.getMeasurement());
			cbe.setValuationQuantity(pcbe.getValuationQuantity());
			cbe.setTrayNumber(pcbe.getTrayNumber());
			cbe.setBulkstockPrice(financeBulkstock.getBulkstockPrice());
			cbe.setEvaluatePrice(financeBulkstock.getEvaluatePrice());
			cbe.setFinancePrice(financeBulkstock.getFinancePrice());
			cbe.setAbnormal(Boolean.TRUE);
			cbe.setAbnormalComment(null);
			cbe.setEnabled(Boolean.TRUE);
			cbe.setCreateDateTime(DateUtil.now());
			cbe.setUpdateDateTime(DateUtil.now());
			cbe.setFilesUuid(pcbe.getFilesUuid());
			containerBulkstockService.createContainerBulkstock(cbe);
			
			pce.setInventoryId(cie.getInventoryId().toString());
			pickupExchangeContainerService.renovatePickupExchangeContainer(pce);
			
			//加锁
			if (1L == ci.getLogisticsCompanyInfoId()) {
				logger.info("换箱同步===");
				HandleSuitcaseResult result = new HandleSuitcaseResult();
				result = faaai.goldLocked(cie.getInventoryId());
				FinanceContainerLogEntity fcle = new FinanceContainerLogEntity();
				fcle.setInventoryId(cie.getInventoryId());
				fcle.setOperator(FinanceSessionContext.getAccountFullName());
				if (result != null) {
					fcle.setRemark("加锁 " + result.getMessage());
				} else {
					fcle.setRemark("加锁失败");
				}
				financeContainerLogService.createFinanceContainerLog(fcle);
			}
		}
	}

	// 验证所提货箱是否存在补货要求(即存在补货要求并且补货还未完成的,存在该情况的抛出存在补货箱的箱信息异常)
	private void validateReplenishContainer(Long[] inventoryIds) {
		List<FinanceCreditReplenishContainerEntity> creditReplenishContainerList = new ArrayList<FinanceCreditReplenishContainerEntity>();
		creditReplenishContainerList = financeCreditReplenishContainerService.inquireCreditReplenishContainerList(inventoryIds);
		for (FinanceCreditReplenishContainerEntity entity : creditReplenishContainerList) {
			if (entity != null && ReplenishStateEnum.FINISHED != entity.getReplenishState()) {
				throw new BusinessException("箱号" + entity.getInventoryId() + "正在补货处理中,无法进行提货处理,请等待补货处理完成,再进行提货");
			}
		}
	}

	@Transactional
	@Override
	public String createNormalPickupApplication(NormalPickupParams params) {
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(params.getFinanceId());
		PickupApplicationEntity pickup = BulkstockPledgeCastor.fromPickupApplication(finance, params);
		if ((ProductTypeEnum.PURCHASING == finance.getProductType() || ProductTypeEnum.PURCHASING_STORAGE == finance.getProductType()) && PickupMethodEnum.CASH_DELIVERY != pickup.getPickupMethod()) {
			throw new BusinessException("代采模式,只允许现金提货");
		}
		if (pickup.getLoanNoticeId() == null && PickupMethodEnum.CASH_DELIVERY != pickup.getPickupMethod()) {
			throw new BusinessException("非现金提货必须指定放款批次ID");
		}
		validatePickupApplication(finance);
		validateReplenishContainer(params.getInventoryIds());
		pickup.setPickupType(PickupTypeEnum.NORMAL);
		if (PickupMethodEnum.EXCHANGE_CONTAINER == pickup.getPickupMethod()) { // 换箱
			pickup.setExchangeStatus(ExchangeStatusEnum.ASSESSMENT);
		}
		pickup.setFinalState(ApiFinanceStateEnum.YW.getCode());
		pickup.setBusinessAuditState(Boolean.TRUE);
		pickup.setAuditState1(Boolean.TRUE);
		pickup.setRiskAuditState(Boolean.TRUE);
		pickup.setRiskMemberAuditState(Boolean.TRUE);
		pickup.setFinalAuditState(Boolean.TRUE);
		pickup.setFinancialAuditState(Boolean.TRUE);
		pickup.setOperationAuditState(Boolean.TRUE);
		pickup.setCeoAuditState(Boolean.TRUE);
		pickup.setCallback(Boolean.FALSE);
		pickup.setAuditState2(Boolean.TRUE);
		
		pickup.setPickupApplicationCreateDateTime(DateUtil.now());
		Long pickupId = pickupApplicationService.createPickupApplicationEntity(pickup);
		//记录审批流程
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), "客户", 1L, pickup.getEnterpriseName() + "发起提货申请", pickupId, 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		
		completePickupBulkstockInventory(finance, params, pickup);
		pickupApplicationService.renovatePickupApplication(pickup);

		// 项目状态更新
		if (PickupMethodEnum.CASH_DELIVERY == pickup.getPickupMethod()) {
			finance.setFinanceState(FinanceStateEnum.PICKUP_APPROVE);
		} else {
			finance.setFinanceState(FinanceStateEnum.EXCHANGE_APPROVE);
		}
		financeApplicationService.renovateFinanceApplication(finance);

		// 项目动态
		createPickupApplicationFinanceProcess(pickup);
		// 发送消息
		FinanceLetterBlockingQueue.putEnterpriseRemindedLetter(getFinanceEnterpriseId(finance.getFinanceId()), "提货申请", "reminded.normal.pickup", pickup.getFinanceNumber(), DateUtils.getCurrentLinkedDateTime(), "提货申请",
				pickup.getPickupNumber());
		
		for (Long inventoryId : params.getInventoryIds()) {
			if (inventoryId != null) {
				FinanceContainerLogEntity fcle = new FinanceContainerLogEntity();
				fcle.setInventoryId(inventoryId);
				fcle.setOperator(FinanceSessionContext.getEnterpriseName());
				fcle.setRemark("提货申请");
				financeContainerLogService.createFinanceContainerLog(fcle);
			}
		}
		return pickupId.toString();
	}

	@Override
	public List<ExchangeInventoryInfo> importExchangeInventory(String fileUuid) {
		List<ExchangeInventoryInfo> eList = ExchangeInventoryCastor.fromExchangeFile(fileUuid);
		return eList;
	}

	@Transactional
	@Override
	public void cancelNormalPickupApplication(Long pickupId) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(pickupId);
		if (ApplicationStateEnum.NOT_APPROVE != persist.getApplicationState()) {
			throw new BusinessException("该提货审批已经处理,不允许取消");
		}
		persist.setApplicationState(ApplicationStateEnum.CANCEL);
		pickupApplicationService.renovatePickupApplication(persist);
		// 释放关联货箱信息
		List<ContainerInventoryEntity> inventoryList = containerInventoryService.inquirePickupContainerInventoryList(pickupId);
		for (ContainerInventoryEntity cie : inventoryList) {
			cie.setPickupId(null);
			cie.setPickupModel(PickupModelEnum.UNKNOWN);
			containerInventoryService.renovateContainerInventory(cie);
		}
	}

	@Transactional
	@Override
	public void consentNormalPickupApplication(Long pickupId, BigDecimal financeValuation, BigDecimal bulkstockInterest, BigDecimal adjustAmount, BigDecimal allowValuation, Integer adjustReson, String adjustment, String auditRemark,
			Long[] exchangeId, BigDecimal[] evaluatePrice, BigDecimal[] lowestPrice, BigDecimal[] highestPrice) {
//		if (adjustAmount != null && adjustAmount.compareTo(BigDecimal.ZERO) > 0) {
//			if (StringUtils.isBlank(adjustment) || adjustReson == null) {
//				throw new BusinessException("有金额调整，原因和说明不允许为空");
//			}
//		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(pickupId);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());

		validatePickupApplication(finance);
//		persist.setFinanceValuation(financeValuation);
//		persist.setBulkstockInterest(bulkstockInterest);
//		persist.setAdjustAmount(adjustAmount);
//		persist.setAdjustReson(adjustReson);
//		persist.setAdjustment(adjustment);
		if (persist.getAdjustAmount() == null) {
			persist.setAdjustAmount(BigDecimal.ZERO);
		}
		if (PickupMethodEnum.CASH_DELIVERY == persist.getPickupMethod()) { // 现金提货
			persist.setAuditAmount(persist.getFinanceValuation().add(persist.getBulkstockInterest()).add(persist.getAdjustAmount()));
		} else { // 换箱&换货
			if (persist.getAdjustAmount()!=null&&persist.getAdjustAmount().compareTo(BigDecimal.ZERO) == 1) {
				throw new BusinessException("换货/换箱不允许金额调整");
			}
			persist.setAuditAmount(BigDecimal.ZERO);
		}
		if (persist.getAuditAmount().compareTo(BigDecimal.ZERO) <= 0) {
			if (PickupMethodEnum.CASH_DELIVERY == persist.getPickupMethod()) { // 现金提货
				persist.setApplicationState(ApplicationStateEnum.RECEIPT);
			} else { // 换箱&换货
				persist.setApplicationState(ApplicationStateEnum.AGREE);
			}
		} else {
			persist.setApplicationState(ApplicationStateEnum.AGREE);
		}
		if (PickupMethodEnum.EXCHANGE_CONTAINER == persist.getPickupMethod()) { // 换箱
			persist.setExchangeStatus(ExchangeStatusEnum.SYNCHRONIZATION);
			List<ContainerInventoryEntity> source = containerInventoryService.inquirePickupExchangeContainerInventoryList(persist.getPickupId());
			List<ContainerInventoryEntity> target = containerInventoryService.inquirePickupContainerInventoryList(persist.getPickupId());

			FinanceContainerEntity financeContainer = financeContainerService.inquireFinanceContainer(persist.getFinanceId());
			financeContainer.setCaseQuantity(financeContainer.getCaseQuantity() - source.size() + target.size());
			financeContainerService.renovateFinanceContainer(financeContainer);
		} else if (PickupMethodEnum.EXCHANGE_BULKSTOCK == persist.getPickupMethod()) { //换货
			List<ContainerInventoryEntity> source = containerInventoryService.inquirePickupExchangeContainerInventoryList(persist.getPickupId());
			FinanceContainerEntity financeContainer = financeContainerService.inquireFinanceContainer(persist.getFinanceId());
			financeContainer.setCaseQuantity(financeContainer.getCaseQuantity() - source.size());
			financeContainerService.renovateFinanceContainer(financeContainer);
		}
		persist.setAuditor(FinanceSessionContext.getAccountFullName());
		persist.setAuditorId(FinanceSessionContext.getAccountId());
		persist.setAuditDateTime(DateUtil.now());
		persist.setAuditRemark(auditRemark);
		persist.setPickupAmount(persist.getAuditAmount());
		persist.setPickupApplicationCreateDateTime(null);
		persist.setDeliveryNoticeCreateDateTime(DateUtil.now());
		persist.setAllowValuation(allowValuation);
//		persist.setReceivedAmount(persist.getPickupAmount());
		
		if (PickupMethodEnum.CASH_DELIVERY == persist.getPickupMethod()) {
			persist.setApplicationState(ApplicationStateEnum.RECEIPT);
		}
		
		pickupApplicationService.renovatePickupApplication(persist);
		processConsentNormalPickupApplication(persist, exchangeId, evaluatePrice, lowestPrice, highestPrice);
		
		if (PickupMethodEnum.CASH_DELIVERY == persist.getPickupMethod()) {
//			List<ContainerInventoryEntity> inventories = containerInventoryService.inquirePickupContainerInventoryList(persist.getPickupId());
//			QuarterSettlementEntity qse = FinanceLoanCastor.fromInterestSettlement1(finance, inventories, null, persist, Boolean.TRUE);
//			persist.setFinanceValuation(qse.getFinanceAmount());
//			persist.setBulkstockInterest(qse.getInterestAmount());
			pickupApplicationService.renovatePickupApplication(persist);
			//提货金额
			FinanceMoneyStatementEntity moneyEntity = FinanceLoanCastor.fromPickupApplication(persist);
			financeMoneyStatementService.createFinanceMoneyStatement(moneyEntity);
			
			//提货利息
			FinanceMoneyStatementEntity moneyEntity1 = FinanceLoanCastor.fromPickupApplicationInterest(persist);
			financeMoneyStatementService.createFinanceMoneyStatement(moneyEntity1);
			
			//其他费用
			FinanceMoneyStatementEntity moneyEntity2 = FinanceLoanCastor.fromPickupApplicationOtherAmount(persist);
			if (BigDecimal.ZERO.compareTo(moneyEntity2.getAmount()) < 0) {
				financeMoneyStatementService.createFinanceMoneyStatement(moneyEntity2);
			}
			
			FinanceMoneyStatementDetailsEntity details = new FinanceMoneyStatementDetailsEntity();
			details.setMoneyStatementId(moneyEntity.getMoneyStatementId());
			details.setCreateDateTime(DateUtils.now());
			details.setEnabled(Boolean.TRUE);
			details.setExpenseName("货物金额");
			details.setExpense(persist.getFinanceValuation());
			details.setPickupId(persist.getPickupId());
			financeMoneyStatementDetailsService.createFinanceMoneyStatementDetails(details);
			FinanceMoneyStatementDetailsEntity details1 = new FinanceMoneyStatementDetailsEntity();
			details1.setMoneyStatementId(moneyEntity.getMoneyStatementId());
			details1.setCreateDateTime(DateUtils.now());
			details1.setEnabled(Boolean.TRUE);
			details1.setExpenseName("货物利息");
			details1.setExpense(BigDecimal.ZERO);
			details1.setPickupId(pickupId);
			financeMoneyStatementDetailsService.createFinanceMoneyStatementDetails(details1);
		}

		// 现金提货 生成保证金退还
		if (PickupMethodEnum.CASH_DELIVERY == persist.getPickupMethod()) { // 现金提货
//			if (finance.getBail().compareTo(finance.getBailAlreadyReturn()) > 0) {
//				// 总箱量
//				FinanceContainerEntity financeContainer = financeContainerService.inquireFinanceContainer(finance.getFinanceId());
//				BigDecimal returnAmount = finance.getBail().divide(new BigDecimal(financeContainer.getCaseQuantity()), 2, BigDecimal.ROUND_HALF_UP);
//				if (finance.getBail().subtract(finance.getBailAlreadyReturn()).compareTo(returnAmount) < 0) {
//					returnAmount = finance.getBail().subtract(finance.getBailAlreadyReturn());
//				}
//				BailReturnEntity bail = new BailReturnEntity();
//				bail.setFinanceId(finance.getFinanceId());
//				bail.setPickupId(pickupId);
//				bail.setFinanceNumber(finance.getFinanceNumber());
//				bail.setAmount(returnAmount);
//				bailReturnService.createBailReturnInfo(bail);
//			}
		} else if (PickupMethodEnum.EXCHANGE_CONTAINER == persist.getPickupMethod()) {
//			生成换箱费
			FinanceMoneyStatementEntity fmse = new FinanceMoneyStatementEntity();
			String em = systemParamService.inquireSytemParamDetailByName("换箱费");
			if (StringUtil.isNotBlank(em)) {
				List<PickupExchangeContainerEntity> pecbes = pickupExchangeContainerService.inquirePickupExchangeContainerList(pickupId);
				fmse.setAmount((new BigDecimal(em)).multiply(new BigDecimal(pecbes.size())));
				fmse.setFinanceId(persist.getFinanceId());
				fmse.setFinanceNumber(persist.getFinanceNumber());
				fmse.setReceiptType(OperatorRoleEnum.PLATFORM.ordinal());
				fmse.setReceiptName(ConfigPropertites.getProperties("platform.name"));
				fmse.setReceiptTenantId(FinanceConstant.DEFAULT_PLATFORM_WEB_TENANT);
				fmse.setDisbursementType(OperatorRoleEnum.ENTERPRISE.ordinal());
				fmse.setDisbursementName(persist.getEnterpriseName());
				fmse.setStatementState(StatementStateEnum.PAID);
				fmse.setStatementSource("EXCHANGE_AMOUNT");
				fmse.setStatementSourceId(persist.getPickupId());
				fmse.setSourceNumber(persist.getPickupNumber());
				fmse.setStatementDate(DateUtil.todayInt());
				fmse.setDisbursementId(persist.getEnterpriseId());
				financeMoneyStatementService.createFinanceMoneyStatement(fmse);
			}
		}

		// 项目状态更新
		finance.setFinanceState(FinanceStateEnum.PICKUP_APPROVED);
		financeApplicationService.renovateFinanceApplication(finance);
		consentPickupApplication(persist);
		
		List<ContainerInventoryEntity> inventories = containerInventoryService.inquirePickupContainerInventoryList(persist.getPickupId());
		for (ContainerInventoryEntity cie : inventories) {
//			cie.setSupervisionState(SupervisionStateEnum.RELIEVE_SUPERVISE);
			FinanceContainerLogEntity fcle = new FinanceContainerLogEntity();
			fcle.setInventoryId(cie.getInventoryId());
			fcle.setOperator(FinanceSessionContext.getAccountFullName());
			if (PickupMethodEnum.CASH_DELIVERY == persist.getPickupMethod()) {
				fcle.setRemark("现金提货审批通过");
			} else if (PickupMethodEnum.EXCHANGE_CONTAINER == persist.getPickupMethod()) {
				fcle.setRemark("换箱申请审批通过");
			} else if (PickupMethodEnum.EXCHANGE_BULKSTOCK == persist.getPickupMethod()) {
				fcle.setRemark("换货申请审批通过");
			}
			financeContainerLogService.createFinanceContainerLog(fcle);
			containerInventoryService.updateContainerInventory(cie);
		}
		
//		if (ProductTypeEnum.MANIFEST_PLEDGE == finance.getProductType()) {
//			StringBuffer recepitIds = new StringBuffer();
//			for (ContainerInventoryEntity cie : inventories) {
//				recepitIds.append(cie.getReceiptId()).append(",");
//				cie.setSignState(Boolean.TRUE);
//				cie.setAbnormal(Boolean.TRUE);
//				cie.setSupervisionState(SupervisionStateEnum.ALREADY_SUPERVISE);
//				containerInventoryService.renovateContainerInventory(cie);
//			}
//			
//			if (recepitIds.length() > 0) {
//				recepitIds.deleteCharAt(recepitIds.length() - 1);
//			}
//			
//			String url = ConfigPropertites.getProperties("finance.outboundNotify.service");
//			Map<String, String> params = new HashMap<>();
//			params.put("receiptId", recepitIds.toString());
//			String responseText = HttpClientHelper.post(url, params);
//			logger.info("url:" + url);
//			logger.info("params:" + params);
//			logger.info("responseText" + responseText);
//			finance.setFinanceState(FinanceStateEnum.SIGN);
//		}
	}
	
	@Override
	@Transactional
	public void supplementPickupAudit1Opinion(PickupAuditInfo params) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getAuditSubmitState1() != null && persist.getAuditSubmitState1()) {
			throw new BusinessException("已提交的审核意见不能更改");
		}
		
		if (Boolean.FALSE == params.getAuditState1() && StringUtil.isBlank(params.getAudit1())) {
			throw new BusinessException("请输入审批意见");
		}
		
		persist.setAudit1(params.getAudit1());
		persist.setAuditDate1(DateUtils.getCurrentLinkedDateTime());
		persist.setAuditor1(FinanceSessionContext.getAccountFullName());
		persist.setAuditorId1(FinanceSessionContext.getAccountId());
		persist.setAuditState1(params.getAuditState1());
		
		pickupApplicationService.renovatePickupApplication(persist);
	}
	
	@Override
	@Transactional
	public void supplementPickupAudit2Opinion(PickupAuditInfo params) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getAuditSubmitState2() != null && persist.getAuditSubmitState2()) {
			throw new BusinessException("已提交的审核意见不能更改");
		}
		
		if (Boolean.FALSE == params.getAuditState2() && StringUtil.isBlank(params.getAudit2())) {
			throw new BusinessException("请输入审批意见");
		}
		
		persist.setAudit2(params.getAudit2());
		persist.setAuditDate2(DateUtils.getCurrentLinkedDateTime());
		persist.setAuditor2(FinanceSessionContext.getAccountFullName());
		persist.setAuditorId2(FinanceSessionContext.getAccountId());
		persist.setAuditState2(params.getAuditState2());
		
		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void supplementPickupBussinessAuditOpinion(PickupAuditInfo params) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getBusinessAuditSubmitState() != null && persist.getBusinessAuditSubmitState()) {
			throw new BusinessException("已提交的审核意见不能更改");
		}
		persist.setBusinessAudit(params.getBusinessAudit());
		persist.setBusinessAuditDate(DateUtils.getCurrentLinkedDateTime());
		persist.setBusinessAuditor(FinanceSessionContext.getAccountFullName());
		persist.setBusinessAuditorId(FinanceSessionContext.getAccountId());
		persist.setBusinessAuditState(params.getBusinessAuditState());
		
		persist.setEvluationFile(params.getEvluationFile());
		if (Boolean.FALSE == params.getBusinessAuditState()) {
			pickupApplicationService.renovatePickupApplication(persist);
			return;
		}
		
		persist.setFinanceValuation(params.getFinanceValuation());
		persist.setBulkstockInterest(params.getBulkstockInterest());
		persist.setAdjustAmount(params.getAdjustAmount());
		persist.setOtherAmount(params.getOtherAmount());
		persist.setAllowValuation(params.getAllowValuation());
		persist.setAdjustReson(params.getAdjustReson());
		persist.setAdjustment(params.getAdjustment());
		persist.setAuditRemark(params.getAuditRemark());
		persist.setInterestInfo(params.getInterestInfo());
		persist.setCallback(Boolean.FALSE);
		//TODO 货物信息
		if (PickupMethodEnum.CASH_DELIVERY == persist.getPickupMethod()) { // 现金提货
			BigDecimal amount=new BigDecimal(0);
			if(persist.getFinanceValuation()!=null)
				amount.add(persist.getFinanceValuation());
			if(persist.getBulkstockInterest()!=null)
				amount.add(persist.getBulkstockInterest());
			if(persist.getAdjustAmount()!=null)
				amount.add(persist.getAdjustAmount());
			persist.setAuditAmount(amount);
		} else { // 换箱&换货
			if (persist.getAdjustAmount() != null && persist.getAdjustAmount().compareTo(BigDecimal.ZERO) == 1) {
				throw new BusinessException("换货/换箱不允许金额调整");
			}
			persist.setAuditAmount(BigDecimal.ZERO);
		}
		
		processConsentNormalPickupApplication(persist, params.getExchangeId(), params.getEvaluatePrice(), params.getLowestPrice(), params.getHighestPrice());
		
		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void supplementPickupOperationAuditOpinion(PickupAuditInfo params) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getOperationAuditSubmitState() != null && persist.getOperationAuditSubmitState()) {
			throw new BusinessException("已提交的审核意见不能更改");
		}
		persist.setOperationAudit(params.getOperationAudit());
		persist.setOperationAuditDate(DateUtils.getCurrentLinkedDateTime());
		persist.setOperationAuditor(FinanceSessionContext.getAccountFullName());
		persist.setOperationAuditorId(FinanceSessionContext.getAccountId());
		persist.setOperationAuditState(params.getOperationAuditState());

		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void supplementPickupFinancialAuditOpinion(PickupAuditInfo params) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getFinancialAuditSubmitState() != null && persist.getFinancialAuditSubmitState()) {
			throw new BusinessException("已提交的审核意见不能更改");
		}
		persist.setFinancialAudit(params.getFinancialAudit());
		persist.setFinancialAuditDate(DateUtils.getCurrentLinkedDateTime());
		persist.setFinancialAuditor(FinanceSessionContext.getAccountFullName());
		persist.setFinancialAuditorId(FinanceSessionContext.getAccountId());
		persist.setFinancialAuditState(params.getFinancialAuditState());

		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void supplementPickupRiskAuditOpinion(PickupAuditInfo params) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getRiskAuditSubmitState() != null && persist.getRiskAuditSubmitState()) {
			throw new BusinessException("已提交的审核意见不能更改");
		}
		
		persist.setRiskAudit(params.getRiskAudit());
		persist.setRiskAuditDate(DateUtils.getCurrentLinkedDateTime());
		persist.setRiskAuditor(FinanceSessionContext.getAccountFullName());
		persist.setRiskAuditorId(FinanceSessionContext.getAccountId());
		persist.setRiskAuditState(params.getRiskAuditState());

		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void supplementPickupRiskMemberAuditOpinion(PickupAuditInfo params) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getRiskMemberAuditSubmitState() != null && persist.getRiskMemberAuditSubmitState()) {
			throw new BusinessException("已提交的审核意见不能更改");
		}
		persist.setRiskMemberAudit(params.getRiskMemberAudit());
		persist.setRiskMemberAuditDate(DateUtils.getCurrentLinkedDateTime());
		persist.setRiskMemberAuditor(FinanceSessionContext.getAccountFullName());
		persist.setRiskMemberAuditorId(FinanceSessionContext.getAccountId());
		persist.setRiskMemberAuditState(params.getRiskMemberAuditState());

		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void supplementPickupCeoAuditOpinion(PickupAuditInfo params) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getCeoAuditSubmitState() != null && persist.getCeoAuditSubmitState()) {
			throw new BusinessException("已提交的审核意见不能更改");
		}
		persist.setCeoAudit(params.getCeoAudit());
		persist.setCeoAuditDate(DateUtils.getCurrentLinkedDateTime());
		persist.setCeoAuditor(FinanceSessionContext.getAccountFullName());
		persist.setCeoAuditorId(FinanceSessionContext.getAccountId());
		persist.setCeoAuditState(params.getCeoAuditState()); 
		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void supplementPickupFinalAuditOpinion(PickupAuditInfo params) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getFinalAuditSubmitState() != null && persist.getFinalAuditSubmitState()) {
			throw new BusinessException("已提交的审核意见不能更改");
		}
		
		if (Boolean.FALSE == params.getFinalAuditState() && StringUtil.isBlank(params.getFinalAudit())) {
			throw new BusinessException("请输入审批意见");
		}
		
		persist.setFinalAudit(params.getFinalAudit());
		persist.setFinalAuditDate(DateUtils.getCurrentLinkedDateTime());
		persist.setFinalAuditor(FinanceSessionContext.getAccountFullName());
		persist.setFinalAuditorId(FinanceSessionContext.getAccountId());
		persist.setFinalAuditState(params.getFinalAuditState());

		pickupApplicationService.renovatePickupApplication(persist);
	}
	
	@Override
	@Transactional
	public void submitPickupAudit1Opinion(PickupAuditInfo params) {
		if (StringUtil.isBlank(params.getDeviceType())) {
			supplementPickupAudit1Opinion(params);
		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getAuditSubmitState1() == Boolean.TRUE) {
			throw new BusinessException("已提交的审批意见不能再次提交");
		}
		
		PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		
		//保存审批流程
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), persist.getAuditState1()?1L:0, "副总经理:" + persist.getAudit1(), persist.getPickupId(), 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		persist.setAuditSubmitState1(Boolean.TRUE);
		if (Boolean.FALSE == params.getAuditState1()) {
			initPickup(persist);
			SendLetterMessage.sendLetterMessage("pickupConsentBusinessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "运营审核"));
		} else {
			persist.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
			consentPickup(persist);
			
//			persist.setFinalState(ApiFinanceStateEnum.TMANAGE.getCode());
//			SendLetterMessage.sendLetterMessage("pickupConsentFinalAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "总经理审核"));
		}
		pickupApplicationService.renovatePickupApplication(persist);
	}
	
	@Override
	@Transactional
	public void submitPickupBussinessAuditOpinion(PickupAuditInfo params) {
		if (StringUtil.isBlank(params.getDeviceType())) {
			supplementPickupBussinessAuditOpinion(params);
		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getBusinessAuditSubmitState() == Boolean.TRUE) {
			throw new BusinessException("已提交的审批意见不能再次提交");
		}
		
		PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		
		//保存审批流程
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), persist.getBusinessAuditState()?1L:0, "运营部:" + persist.getBusinessAudit(), persist.getPickupId(), 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		
		if (Boolean.FALSE == params.getBusinessAuditState()) {
//			persist.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
//			opposeNormalPickupApplication(persist.getPickupId(), null, persist.getBusinessAudit());
			initPickup(persist);
		} else {
			persist.setBusinessAuditSubmitState(Boolean.TRUE);
			if (PickupMethodEnum.CASH_DELIVERY == persist.getPickupMethod()) {
				persist.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
				SendLetterMessage.sendLetterMessage("pickupConsentRiskAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "资金审核"));
			} else {
				persist.setFinalState(ApiFinanceStateEnum.FK.getCode());
				SendLetterMessage.sendLetterMessage("pickupConsentFinancialAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "风控审核"));
			}
		}
		
		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void submitPickupOperationAuditOpinion(PickupAuditInfo params) {
		if (StringUtil.isBlank(params.getDeviceType())) {
			supplementPickupOperationAuditOpinion(params);
		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getOperationAuditSubmitState() == Boolean.TRUE) {
			throw new BusinessException("已提交的审批意见不能再次提交");
		}
		
		PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		persist.setOperationAuditSubmitState(Boolean.TRUE);
		//记录审批
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), persist.getOperationAuditState()?1L:0, "风控领导:" + persist.getOperationAudit(), persist.getPickupId(), 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		if (Boolean.FALSE == params.getOperationAuditState()) {
			initPickup(persist);
			SendLetterMessage.sendLetterMessage("pickupConsentBusinessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "运营审核"));
		} else {
			if (PickupMethodEnum.CASH_DELIVERY != persist.getPickupMethod()) {
				persist.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				consentPickup(persist);
			} else {
				persist.setFinalState(ApiFinanceStateEnum.FMANAGE.getCode());
				SendLetterMessage.sendLetterMessage("pickupConsentFinalAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "副总经理审核"));
			}
		}
		pickupApplicationService.renovatePickupApplication(persist);
	}
	
	private void consentPickup(PickupApplicationEntity persist) {
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		List<PickupExchangeEntity> exchanges = pickupExchangeService.inquirePickupExchangeList(persist);
		List<Long> exchangeId = new ArrayList<>();
		List<BigDecimal> highestPrise = new ArrayList<>();
		List<BigDecimal> lowestPrice = new ArrayList<>();
		List<BigDecimal> evaluatePrice = new ArrayList<>();
		for (PickupExchangeEntity pee : exchanges) {
			exchangeId.add(pee.getExchangeId());
			highestPrise.add(pee.getHighestPrice());
			lowestPrice.add(pee.getLowestPrice());
			evaluatePrice.add(pee.getEvaluatePrice());
		}
		consentNormalPickupApplication(persist.getPickupId(), persist.getFinanceValuation(), persist.getBulkstockInterest(), persist.getAdjustAmount(), persist.getAllowValuation(), persist.getAdjustReson(), persist.getAdjustment(), persist.getAuditRemark(), exchangeId.toArray(new Long[exchangeId.size()]), evaluatePrice.toArray(new BigDecimal[evaluatePrice.size()]), lowestPrice.toArray(new BigDecimal[lowestPrice.size()]), highestPrise.toArray(new BigDecimal[highestPrise.size()]));
		List<FinanceBulkstockEntity> fbes = financeBulkstockService.inquireFinanceBulkstockList(persist.getFinanceId());
		List<ContainerInventoryEntity> source = containerInventoryService.inquirePickupExchangeContainerInventoryList(persist.getPickupId());
		FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(persist.getPickupId(), fbes.get(0).getBulkstockName(), fbes.get(0).getQuantity(), fbes.get(0).getUnit(), ApiTypeEnum.TH.getCode(), persist.getPickupNumber(), DateUtil.now(), persist.getEnterpriseName(), finance.getProductName(), Long.valueOf(source.size()));
		financeAuditLogService.createFinanceCompleteResultEntity(fcre);
	}

	@Override
	@Transactional
	public void submitPickupFinancialAuditOpinion(PickupAuditInfo params) {
		if (StringUtil.isBlank(params.getDeviceType())) {
			supplementPickupFinancialAuditOpinion(params);
		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getFinancialAuditSubmitState() == Boolean.TRUE) {
			throw new BusinessException("已提交的审批意见不能再次提交");
		}
		
		PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		persist.setFinancialAuditSubmitState(Boolean.TRUE);
		persist.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
		//保存审批流程
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), persist.getFinancialAuditState()?1L:0, "风控部:" + persist.getFinancialAudit(), persist.getPickupId(), 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		
		if (Boolean.FALSE == params.getFinancialAuditState()) {
			initPickup(persist);
			SendLetterMessage.sendLetterMessage("pickupConsentCeoAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "运营审核"));
		} else {
			SendLetterMessage.sendLetterMessage("pickupConsentOperationAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "风控领导审核"));
		}
		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void submitPickupRiskAuditOpinion(PickupAuditInfo params) {
		if (StringUtil.isBlank(params.getDeviceType())) {
			supplementPickupRiskAuditOpinion(params);
		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getRiskAuditSubmitState() == Boolean.TRUE) {
			throw new BusinessException("已提交的审批意见不能再次提交");
		}
		
		PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		persist.setRiskAuditSubmitState(Boolean.TRUE);
		persist.setFinalState(ApiFinanceStateEnum.ZJMANAGE.getCode());
		//保存审批流程
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), persist.getRiskAuditState()?1L:0, "资金部:" + persist.getRiskAudit(), persist.getPickupId(), 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		
		if (Boolean.FALSE == params.getRiskAuditState()) {
			initPickup(persist);
			SendLetterMessage.sendLetterMessage("pickupConsentCeoAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "运营审核"));
		} else {
			SendLetterMessage.sendLetterMessage("pickupConsentRiskMemberAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "资金领导审核"));
		}
		
		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void submitPickupRiskMemberAuditOpinion(PickupAuditInfo params) {
		if (StringUtil.isBlank(params.getDeviceType())) {
			supplementPickupRiskMemberAuditOpinion(params);
		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getRiskMemberAuditSubmitState() == Boolean.TRUE) {
			throw new BusinessException("已提交的审批意见不能再次提交");
		}
		
		PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		persist.setRiskMemberAuditSubmitState(Boolean.TRUE);
		persist.setFinalState(ApiFinanceStateEnum.FK.getCode());
		//保存审批流程
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), persist.getRiskMemberAuditState()?1L:0, "资金领导:" + persist.getRiskMemberAudit(), persist.getPickupId(), 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		if (Boolean.FALSE == params.getRiskMemberAuditState()) {
			initPickup(persist);
			SendLetterMessage.sendLetterMessage("pickupConsentBusinessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "运营审核"));
		} else {
			SendLetterMessage.sendLetterMessage("pickupConsentFinancialAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "风控审核"));
		}
		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void submitPickupCeoAuditOpinion(PickupAuditInfo params) {
		if (StringUtil.isBlank(params.getDeviceType())) {
			supplementPickupCeoAuditOpinion(params);
		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getCeoAuditSubmitState() == Boolean.TRUE) {
			throw new BusinessException("已提交的审批意见不能再次提交");
		}
		
		PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		//保存审批流程
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), persist.getCeoAuditState()?1L:0, "商务部:" + persist.getCeoAudit(), persist.getPickupId(), 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		if (Boolean.FALSE == params.getCeoAuditState()) {
			persist.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
			opposeNormalPickupApplication(persist.getPickupId(), null, persist.getBusinessAudit());
			initPickup(persist);
		} else {
			persist.setCeoAuditSubmitState(Boolean.TRUE);
			persist.setFinalState(ApiFinanceStateEnum.YY.getCode());
		}
		
		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	@Transactional
	public void submitPickupFinalAuditOpinion(PickupAuditInfo params) {
		if (StringUtil.isBlank(params.getDeviceType())) {
			supplementPickupFinalAuditOpinion(params);
		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getFinalAuditSubmitState() == Boolean.TRUE) {
			throw new BusinessException("已提交的审批意见不能再次提交");
		}
		
		PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		//保存审批流程
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), persist.getFinalAuditState()?1L:0, "总经理:" + persist.getFinalAudit(), persist.getPickupId(), 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		persist.setFinalAuditSubmitState(Boolean.TRUE);
		if (Boolean.FALSE == params.getFinalAuditState()) {
			initPickup(persist);
			SendLetterMessage.sendLetterMessage("pickupConsentBusinessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "运营审核"));
		} else {
			persist.setFinalState(ApiFinanceStateEnum.ZXMANAGE.getCode());
		}
		pickupApplicationService.renovatePickupApplication(persist);
	}
	
	@Override
	@Transactional
	public void submitPickupAudit2Opinion(PickupAuditInfo params) {
		if (StringUtil.isBlank(params.getDeviceType())) {
			supplementPickupAudit2Opinion(params);
		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(params.getPickupId());
		if (persist.getAuditSubmitState2() == Boolean.TRUE) {
			throw new BusinessException("已提交的审批意见不能再次提交");
		}
		
		PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		//保存审批流程
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), persist.getAuditState2()?1L:0, "董事长:" + persist.getAudit2(), persist.getPickupId(), 3L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		persist.setAuditSubmitState2(Boolean.TRUE);
		if (Boolean.FALSE == params.getAuditState2()) {
			initPickup(persist);
			SendLetterMessage.sendLetterMessage("pickupConsentBusinessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "运营审核"));
		} else {
			persist.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
			consentPickup(persist);
		}
		pickupApplicationService.renovatePickupApplication(persist);
	}
	
	private void initPickup(PickupApplicationEntity pickup){
		pickup.setFinalState(ApiFinanceStateEnum.YW.getCode());
		
		pickup.setBusinessAuditState(Boolean.TRUE);
		pickup.setAuditState1(Boolean.TRUE);
		pickup.setRiskAuditState(Boolean.TRUE);
		pickup.setRiskMemberAuditState(Boolean.TRUE);
		pickup.setFinalAuditState(Boolean.TRUE);
		pickup.setFinancialAuditState(Boolean.TRUE);
		pickup.setOperationAuditState(Boolean.TRUE);
		pickup.setCeoAuditState(Boolean.TRUE);
		pickup.setAuditState2(Boolean.TRUE);
		
		pickup.setBusinessAuditSubmitState(Boolean.FALSE);
		pickup.setAuditSubmitState1(Boolean.FALSE);
		pickup.setRiskAuditSubmitState(Boolean.FALSE);
		pickup.setRiskMemberAuditSubmitState(Boolean.FALSE);
		pickup.setFinalAuditSubmitState(Boolean.FALSE);
		pickup.setFinancialAuditSubmitState(Boolean.FALSE);
		pickup.setOperationAuditSubmitState(Boolean.FALSE);
		pickup.setCeoAuditSubmitState(Boolean.FALSE);
		pickup.setAuditSubmitState2(Boolean.FALSE);
		
		pickup.setBusinessAudit(null);
		pickup.setAudit1(null);
		pickup.setRiskAudit(null);
		pickup.setRiskMemberAudit(null);
		pickup.setFinalAudit(null);
		pickup.setFinancialAudit(null);
		pickup.setOperationAudit(null);
		pickup.setCeoAudit(null);
		pickup.setAudit2(null);
		
		pickup.setBusinessAuditor(null);
		pickup.setAuditor1(null);
		pickup.setRiskAuditor(null);
		pickup.setRiskMemberAuditor(null);
		pickup.setFinalAuditor(null);
		pickup.setFinancialAuditor(null);
		pickup.setOperationAuditor(null);
		pickup.setCeoAuditor(null);
		pickup.setAuditor2(null);
		
		pickup.setBusinessAuditorId(null);
		pickup.setAuditorId1(null);
		pickup.setRiskAuditorId(null);
		pickup.setRiskMemberAuditorId(null);
		pickup.setFinalAuditorId(null);
		pickup.setFinancialAuditorId(null);
		pickup.setOperationAuditorId(null);
		pickup.setCeoAuditorId(null);
		pickup.setAuditorId2(null);
		
		pickup.setBusinessAuditDate(null);
		pickup.setAuditDate1(null);
		pickup.setRiskAuditDate(null);
		pickup.setRiskMemberAuditDate(null);
		pickup.setFinalAuditDate(null);
		pickup.setFinancialAuditDate(null);
		pickup.setOperationAuditDate(null);
		pickup.setCeoAuditDate(null);
		pickup.setAuditDate2(null);
		
		pickup.setCallback(Boolean.TRUE);
	}

	@Transactional
	@Override
	public void syncNormalPickupExchangeContainer(Long containerId) {
		PickupExchangeContainerEntity pece = pickupExchangeContainerService.inquirePickupExchangeContainerDetail(containerId);
		PickupApplicationEntity pickup = pickupApplicationService.inquirePickupApplication(pece.getPickupId());
		if (PickupMethodEnum.EXCHANGE_CONTAINER != pickup.getPickupMethod()) {
			throw new BusinessException("该箱来源非换箱提货");
		}
		Boolean syncResult = TallyingDeliveryCastor.syncExchangeContainer(pece);
		if (syncResult) {
			pickupExchangeContainerService.renovatePickupExchangeContainer(pece);
			pickupExchangeContainerBulkstockService.renovatePickupExchangeContainerBulkstock(pece.getPickupExchangeContainerBulkstockEntity());
			List<PickupExchangeContainerEntity> peces = pickupExchangeContainerService.inquirePickupExchangeContainerList(pece.getPickupId());
			boolean sync = true;
			for (PickupExchangeContainerEntity p : peces) {
				if (p.getTallyDateTime() == null) {
					sync = false;
				}
			}
			if (sync) { // 理货同步完成
				pickup.setExchangeStatus(ExchangeStatusEnum.CONCLUDE);
				pickupApplicationService.renovatePickupApplication(pickup);
			}
		}
	}
	
	@Transactional
	@Override
	public void syncNormalPickupExchangeContainerAll(Long pickupId) {
		PickupApplicationEntity pickup = pickupApplicationService.inquirePickupApplication(pickupId);
		List<PickupExchangeContainerEntity> peces = pickupExchangeContainerService.inquirePickupExchangeContainerList(pickupId);
		for (PickupExchangeContainerEntity pece : peces) {
			if (Boolean.TRUE == TallyingDeliveryCastor.syncExchangeContainer(pece)) {
				pickupExchangeContainerService.renovatePickupExchangeContainer(pece);
				pickupExchangeContainerBulkstockService.renovatePickupExchangeContainerBulkstock(pece.getPickupExchangeContainerBulkstockEntity());
			}
		}
		
		boolean sync = true;
		for (PickupExchangeContainerEntity p : peces) {
			if (p.getTallyDateTime() == null) {
				sync = false;
			}
		}
		if (sync) { // 理货同步完成
			pickup.setExchangeStatus(ExchangeStatusEnum.CONCLUDE);
			pickupApplicationService.renovatePickupApplication(pickup);
		}
	}

	@Override
	@Transactional
	public void protocolNormalPickupApplication(Long pickupId, String protocolUuids) {
		PickupApplicationEntity pickup = pickupApplicationService.inquirePickupApplication(pickupId);
		if (ExchangeStatusEnum.CONCLUDE != pickup.getExchangeStatus()) {
			throw new BusinessException("换箱信息理货数据还未同步完成");
		}
		if (PickupMethodEnum.EXCHANGE_CONTAINER != pickup.getPickupMethod()) {
			throw new BusinessException("该提货申请非换箱申请");
		}
		pickup.setProtocolUuids(protocolUuids);
		pickup.setExchangeStatus(ExchangeStatusEnum.FINISHED);
		pickupApplicationService.renovatePickupApplication(pickup);
		// 货箱转移
		protocolNormalPickupApplicationExchangeContainer(pickup);
	}

	@Transactional
	@Override
	public void opposeNormalPickupApplication(Long pickupId, Integer disagreeReson, String auditRemark) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(pickupId);
		persist.setApplicationState(ApplicationStateEnum.DISAGREE);
		persist.setDisagreeReson(disagreeReson);
		persist.setAuditor(FinanceSessionContext.getAccountFullName());
		persist.setAuditorId(FinanceSessionContext.getAccountId());
		persist.setAuditDateTime(DateUtil.now());
		persist.setAuditRemark(auditRemark);
		pickupApplicationService.renovatePickupApplication(persist);

		// 项目状态更新
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		if (PickupMethodEnum.CASH_DELIVERY == persist.getPickupMethod()) {
			financeEntity.setFinanceState(FinanceStateEnum.PICKUP_APPROVE_NOPASS);
		} else {
			financeEntity.setFinanceState(FinanceStateEnum.EXCHANGE_APPROVE_NOPASS);
		}
		financeApplicationService.renovateFinanceApplication(financeEntity);

		opposePickupApplication(persist);
	}

	@Transactional
	@Override
	public void breakNormalPickupContract(Long pickupId, String breachContract) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(pickupId);
		persist.setApplicationState(ApplicationStateEnum.DISAGREE);
		pickupApplicationService.renovatePickupApplication(persist);
	}

	@Override
	public PickupApplicationDetail inquireNormalPickupApplicationDetail(Long pickupId) {
		PickupApplicationEntity entity = pickupApplicationService.inquirePickupApplication(pickupId);
		return BulkstockPledgeCastor.toPickupApplicationDetail(entity);
	}
	
	@Transactional
	@Override
	public void updatePickupApplicationDetails(Long containerId, String waybillNumber, String caseNumber) {
		PickupExchangeContainerEntity entity = pickupExchangeContainerService.inquirePickupExchangeContainerDetail(containerId);
		entity.setWaybillNumber(waybillNumber);
		entity.setCaseNumber(caseNumber);
		PersistUtil.update(entity);
	}
	@Override
	public ExchangeContainerInventory inquireExchangeContainerInventoryDetail(Long containerId) {
		PickupExchangeContainerEntity entity = pickupExchangeContainerService.inquirePickupExchangeContainerDetail(containerId);
		ExchangeContainerInventory exchangeContainerInventory = new ExchangeContainerInventory();
		BeanUtils.copyProperties(entity, exchangeContainerInventory);
		exchangeContainerInventory.setTallyExAbnormalState(entity.getTallyExAbnormalState() == null ? 0 : entity.getTallyExAbnormalState().ordinal());
		List<PickupExchangeContainerBulkstockEntity> pickupExchangeContainerBulkstockEntityList = pickupExchangeContainerBulkstockService.inquirePickupExchangeContainerBulkstockList(containerId);
		if (pickupExchangeContainerBulkstockEntityList.size() > 0) {
			List<ExchangeContainerBulkstock> bList = new ArrayList<ExchangeContainerBulkstock>();
			for (PickupExchangeContainerBulkstockEntity pcbe : pickupExchangeContainerBulkstockEntityList) {
				ExchangeContainerBulkstock exchangeContainerBulkstock = BulkstockPledgeCastor.toExchangeBulkstockInfo(pcbe);
				bList.add(exchangeContainerBulkstock);
			}
			exchangeContainerInventory.setExchangeContainerBulkstock(bList);
		}
		return exchangeContainerInventory;
	}

	@Override
	public PageList<PickupApplicationLineInfo> inquireNormalPickupApplicationPageList(Long[] pickupIds, Long enterpriseId, Long financeId, String financeNumber, String dateBegin, String dateEnd, Integer applicationState,
			String waybillNumber, String caseNumber, String enterpriseName, Integer productType, String bulkstockName,Integer pickupMethod, String pickupNumber, PageCriteria page) {
		if (FinanceSessionContext.isEnterprise()) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		ApplicationSimpleStateEnum _enum = null;
		if (applicationState != null) {
			_enum = ApplicationSimpleStateEnum.valueOf(applicationState);
		}
		Date beginDate = null;
		Date endDate = null;
		if (StringUtil.isNotBlank(dateBegin)) {
			beginDate = DateUtil.from(dateBegin);
		}
		if (StringUtil.isNotBlank(dateBegin)) {
			endDate = DateUtil.from(dateEnd);
		}
		if (StringUtil.isNotBlank(waybillNumber) || StringUtil.isNotBlank(caseNumber)) {
			List<Long> pickupId1s = containerInventoryService.inquirePickupIdFromContainerInventory(waybillNumber, caseNumber);
			if (pickupIds != null && pickupIds.length > 0) {
				Vector<Long> pis = new Vector<>();
				for (Long p : pickupId1s) {
					if (Arrays.asList(pickupIds).contains(p)){
						pis.add(p);
					}
				}
				pickupIds = pis.toArray(new Long[pis.size()]);
				if (pis.size() == 0) {
					pickupIds = new Long[]{-1L};
				}
			} else {
				pickupIds = pickupId1s.toArray(new Long[pickupId1s.size()]);
			}
		}
		List<Long> financeIds = financeApplicationService.getFinanceListIds(productType);
//		PageList<PickupApplicationEntity> pages = pickupApplicationService.inquirePickupApplicationPageList(pickupIds, enterpriseId, financeId, financeNumber, _enum, PickupTypeEnum.NORMAL, beginDate, endDate, page);
		PageList<PickupApplicationEntity> pages = pickupApplicationService.inquirePickupApplicationPageLists(financeIds,pickupIds, enterpriseId, financeId, financeNumber, _enum, PickupTypeEnum.NORMAL, beginDate, endDate, enterpriseName,bulkstockName, pickupMethod, pickupNumber, page);
		PageList<PickupApplicationLineInfo> results = new PageList<>(page, pages.getTotalRecordCount());
		for (PickupApplicationEntity entity : pages) {
			results.add(BulkstockPledgeCastor.toPickupApplicationLineInfo(entity));
		}
		return results;
	}
	
	@Override
	public List<PickupApplicationDetail> inquireNormalPickupApplicationList(String enterpriseName, String dateBegin,
			String dateEnd, String waybillNumber, String caseNumber) {
		Date beginDate = null;
		Date endDate = null;
		if (StringUtil.isNotBlank(dateBegin)) {
			beginDate = DateUtil.from(dateBegin);
		}
		if (StringUtil.isNotBlank(dateBegin)) {
			endDate = DateUtil.from(dateEnd);
		}
		Long[] ps = null;
		if (StringUtil.isNotBlank(waybillNumber) || StringUtil.isNotBlank(caseNumber)) {
			List<Long> pickupIds = containerInventoryService.inquirePickupIdFromContainerInventory(waybillNumber, caseNumber);
			ps = pickupIds.toArray(new Long[pickupIds.size()]);
		}
		List<PickupApplicationEntity> list = pickupApplicationService.inquirePickupApplicationList(null, null, null, enterpriseName, beginDate, endDate, ps);
		List<PickupApplicationDetail> results = new ArrayList<>();
		for (PickupApplicationEntity pae : list) {
			PickupApplicationDetail detail = BulkstockPledgeCastor.toPickupApplicationDetail(pae);
			results.add(detail);
		}
		return results;
	}

	// =======================================================================================================================================================//
	@Transactional
	@Override
	public String createPrePickupApplication(AppointPickupParams params) {
		if (params.getInventoryIds() == null || params.getInventoryIds().length == 0) {
			throw new BusinessException("货物信息不允许为空");
		}
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(params.getFinanceId());
		validatePickupApplication(finance);
		validateReplenishContainer(params.getInventoryIds());

		params.setPickupMethod(1);
		PickupApplicationEntity pickup = BulkstockPledgeCastor.fromPickupApplication(finance, params);
		pickup.setPickupType(PickupTypeEnum.AHEAD);
		pickup.setApplicationPreCreateDateTime(DateUtils.now());
		Long pickupId = pickupApplicationService.createPickupApplicationEntity(pickup);
		completePickupBulkstockInventory(finance, params, pickup);
		pickupApplicationService.renovatePickupApplication(pickup);
		// 项目动态
		createPickupApplicationFinanceProcess(pickup);
		// 发送消息
		FinanceLetterBlockingQueue.putEnterpriseRemindedLetter(getFinanceEnterpriseId(finance.getFinanceId()), "提前还款申请", "reminded.normal.pickup", pickup.getFinanceNumber(), DateUtils.getCurrentLinkedDateTime(), "提前还款申请",
				pickup.getPickupNumber());
		return pickupId.toString();
	}

	@Transactional
	@Override
	public void cancelPrePickupApplication(Long pickupId) {
		PickupApplicationEntity entity = pickupApplicationService.inquirePickupApplication(pickupId);
		entity.setApplicationState(ApplicationStateEnum.CANCEL);
		pickupApplicationService.updatePickupApplication(entity);

		// 释放关联货箱信息
		List<ContainerInventoryEntity> inventoryList = containerInventoryService.inquirePickupContainerInventoryList(pickupId);
		for (ContainerInventoryEntity cie : inventoryList) {
			cie.setPickupId(null);
			cie.setPickupModel(PickupModelEnum.UNKNOWN);
			containerInventoryService.renovateContainerInventory(cie);
		}
	}

	@Transactional
	@Override
	public void consentPrePickupApplication(Long pickupId, BigDecimal financeValuation, BigDecimal bulkstockInterest, BigDecimal adjustAmount, Integer adjustReson, String adjustment, String auditRemark) {
//		if (adjustAmount != null && !adjustAmount.equals(BigDecimal.ZERO)) {
//			if (StringUtils.isBlank(adjustment) || adjustReson == null) {
//				throw new BusinessException("有金额调整，原因和说明不允许为空");
//			}
//		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(pickupId);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		validatePickupApplication(finance);

		persist.setFinanceValuation(financeValuation);
		persist.setBulkstockInterest(bulkstockInterest);
		persist.setAdjustAmount(adjustAmount);
		persist.setAdjustReson(adjustReson);
		persist.setAdjustment(adjustment);
		persist.setApplicationState(ApplicationStateEnum.AGREE);
		persist.setAuditAmount(persist.getFinanceValuation().add(persist.getBulkstockInterest()).add(persist.getAdjustAmount()));
		persist.setAuditor(FinanceSessionContext.getAccountFullName());
		persist.setAuditorId(FinanceSessionContext.getAccountId());
		persist.setAuditDateTime(DateUtil.now());
		persist.setAuditRemark(auditRemark);
		persist.setPickupAmount(persist.getAuditAmount());
		persist.setApplicationPreCreateDateTime(null);
		persist.setReceiveConfirmCreateDateTime(DateUtil.now());
		pickupApplicationService.renovatePickupApplication(persist);

		consentPickupApplication(persist);
	}

	@Transactional
	@Override
	public void opposePrePickupApplication(Long pickupId, Integer disagreeReson, String auditRemark) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(pickupId);
		persist.setApplicationState(ApplicationStateEnum.DISAGREE);
		persist.setDisagreeReson(disagreeReson);
		persist.setAuditor(FinanceSessionContext.getAccountFullName());
		persist.setAuditorId(FinanceSessionContext.getAccountId());
		persist.setAuditDateTime(DateUtil.now());
		persist.setAuditRemark(auditRemark);
		pickupApplicationService.renovatePickupApplication(persist);

		opposePickupApplication(persist);
	}

	@Override
	public PickupApplicationDetail inquirePrePickupApplicationDetail(Long pickupId) {
		PickupApplicationEntity entity = pickupApplicationService.inquirePickupApplication(pickupId);
		return BulkstockPledgeCastor.toPickupApplicationDetail(entity);
	}

	@Override
	public PageList<PickupApplicationLineInfo> inquirePrePickupApplicationPageList(Long[] pickupIds, Long enterpriseId, Long financeId, String financeNumber, String dateBegin, String dateEnd, Integer applicationState, PageCriteria page) {
		if (FinanceSessionContext.isEnterprise()) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		ApplicationSimpleStateEnum _enum = null;
		if (applicationState != null) {
			_enum = ApplicationSimpleStateEnum.valueOf(applicationState);
		}
		Date beginDate = null;
		Date endDate = null;
		if (StringUtil.isNotBlank(dateBegin)) {
			beginDate = DateUtil.from(dateBegin);
		}
		if (StringUtil.isNotBlank(dateBegin)) {
			endDate = DateUtil.from(dateEnd);
		}
		PageList<PickupApplicationEntity> pages = pickupApplicationService.inquirePickupApplicationPageList(pickupIds, enterpriseId, financeId, financeNumber, _enum, PickupTypeEnum.AHEAD, beginDate, endDate, page);
		PageList<PickupApplicationLineInfo> results = new PageList<>(page, pages.getTotalRecordCount());
		for (PickupApplicationEntity entity : pages) {
			results.add(BulkstockPledgeCastor.toPickupApplicationLineInfo(entity));
		}
		return results;
	}

	// ====================================================================================================================================================================//
	@Transactional
	@Override
	public String createRansomPickupApplication(AppointPickupParams params) {
		if (params.getInventoryIds() == null || params.getInventoryIds().length == 0) {
			throw new BusinessException("货物信息不允许为空");
		}
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(params.getFinanceId());
		validatePickupApplication(finance);
		validateReplenishContainer(params.getInventoryIds());

		params.setPickupMethod(1);
		PickupApplicationEntity pickup = BulkstockPledgeCastor.fromPickupApplication(finance, params);
		pickup.setPickupType(PickupTypeEnum.REDEEM);
		pickup.setApplicationRedeemCreateDateTime(DateUtil.now());
		Long pickupId = pickupApplicationService.createPickupApplicationEntity(pickup);
		completePickupBulkstockInventory(finance, params, pickup);
		pickupApplicationService.renovatePickupApplication(pickup);
		// 项目动态
		createPickupApplicationFinanceProcess(pickup);
		// 发送消息
		FinanceLetterBlockingQueue.putEnterpriseRemindedLetter(getFinanceEnterpriseId(finance.getFinanceId()), "赎货申请", "reminded.normal.pickup", pickup.getFinanceNumber(), DateUtils.getCurrentLinkedDateTime(), "赎货申请",
				pickup.getPickupNumber());
		return pickupId.toString();
	}

	@Transactional
	@Override
	public void cancelRansomPickupApplication(Long pickupId) {
		PickupApplicationEntity entity = pickupApplicationService.inquirePickupApplication(pickupId);
		entity.setApplicationState(ApplicationStateEnum.CANCEL);
		pickupApplicationService.updatePickupApplication(entity);

		// 释放关联货箱信息
		List<ContainerInventoryEntity> inventoryList = containerInventoryService.inquirePickupContainerInventoryList(pickupId);
		for (ContainerInventoryEntity cie : inventoryList) {
			cie.setPickupId(null);
			cie.setPickupModel(PickupModelEnum.UNKNOWN);
			containerInventoryService.renovateContainerInventory(cie);
		}
	}

	@Transactional
	@Override
	public void consentRansomPickupApplication(Long pickupId, BigDecimal financeValuation, BigDecimal bulkstockInterest, BigDecimal adjustAmount, Integer adjustReson, String adjustment, String auditRemark) {
//		if (adjustAmount != null) {
//			if (StringUtils.isBlank(adjustment) || adjustReson == null) {
//				throw new BusinessException("有金额调整，原因和说明不允许为空");
//			}
//		}
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(pickupId);

		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		validatePickupApplication(finance);

		persist.setFinanceValuation(financeValuation);
		persist.setBulkstockInterest(bulkstockInterest);
		persist.setAdjustAmount(adjustAmount);
		persist.setAdjustReson(adjustReson);
		persist.setAdjustment(adjustment);
		persist.setApplicationState(ApplicationStateEnum.AGREE);
		persist.setAuditAmount(persist.getFinanceValuation().add(persist.getBulkstockInterest()).add(persist.getAdjustAmount()));
		persist.setAuditor(FinanceSessionContext.getAccountFullName());
		persist.setAuditorId(FinanceSessionContext.getAccountId());
		persist.setAuditDateTime(DateUtil.now());
		persist.setAuditRemark(auditRemark);
		persist.setPickupAmount(persist.getAuditAmount());
		persist.setApplicationRedeemCreateDateTime(null);
		persist.setReceiveConfirmCreateDateTime(DateUtil.now());
		pickupApplicationService.renovatePickupApplication(persist);

		consentPickupApplication(persist);
	}

	@Transactional
	@Override
	public void opposeRansomPickupApplication(Long pickupId, Integer disagreeReson, String auditRemark) {
		PickupApplicationEntity persist = pickupApplicationService.inquirePickupApplication(pickupId);
		persist.setApplicationState(ApplicationStateEnum.DISAGREE);
		persist.setDisagreeReson(disagreeReson);
		persist.setAuditor(FinanceSessionContext.getAccountFullName());
		persist.setAuditorId(FinanceSessionContext.getAccountId());
		persist.setAuditDateTime(DateUtil.now());
		persist.setAuditRemark(auditRemark);
		pickupApplicationService.renovatePickupApplication(persist);

		opposePickupApplication(persist);
	}

	@Override
	public PickupApplicationDetail inquireRansomPickupApplicationDetail(Long pickupId) {
		PickupApplicationEntity entity = pickupApplicationService.inquirePickupApplication(pickupId);
		return BulkstockPledgeCastor.toPickupApplicationDetail(entity);
	}

	@Override
	public PageList<PickupApplicationLineInfo> inquireRansomPickupApplicationPageList(Long[] pickupIds, Long enterpriseId, Long financeId, String financeNumber, String dateBegin, String dateEnd, Integer applicationState,
			PageCriteria page) {
		if (FinanceSessionContext.isEnterprise()) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		ApplicationSimpleStateEnum _enum = null;
		if (applicationState != null) {
			_enum = ApplicationSimpleStateEnum.valueOf(applicationState);
		}
		Date beginDate = null;
		Date endDate = null;
		if (StringUtil.isNotBlank(dateBegin)) {
			beginDate = DateUtil.from(dateBegin);
		}
		if (StringUtil.isNotBlank(dateBegin)) {
			endDate = DateUtil.from(dateEnd);
		}
		PageList<PickupApplicationEntity> pages = pickupApplicationService.inquirePickupApplicationPageList(pickupIds, enterpriseId, financeId, financeNumber, _enum, PickupTypeEnum.REDEEM, beginDate, endDate, page);
		PageList<PickupApplicationLineInfo> results = new PageList<>(page, pages.getTotalRecordCount());
		for (PickupApplicationEntity entity : pages) {
			results.add(BulkstockPledgeCastor.toPickupApplicationLineInfo(entity));
		}
		return results;
	}

	// =======================================================================================================================================================================================//
	@Transactional
	@Override
	public String createPickupDelayApplication(Long pickupId, String deliveryDate, BigDecimal estimateDelayAmount, Integer delayReson, String delayRemark) {
		PickupApplicationEntity pickupEntity = pickupApplicationService.inquirePickupApplication(pickupId);
		PickupDelayApplicationEntity delayEntity = BulkstockPledgeCastor.fromPickupDelayApplication(pickupEntity, deliveryDate, estimateDelayAmount);
		delayEntity.setDelayRemark(delayRemark);
		delayEntity.setDelayReson(delayReson);
		delayEntity.setPickupDelayCreateDateTime(DateUtil.now());
		Long pickupDelayId = pickupDelayApplicationService.createPickupDelayApplication(delayEntity);

		// 项目动态
		FinanceProcessDetailEntity processDetailEntity = FinanceProcessCastor.fromPickupDelayApplication(delayEntity, null, null);
		if (processDetailEntity != null && LongUtils.isPrimaryKey(processDetailEntity.getProcessDetailId())) {
			financeProcessDetailService.renovateFinanceProcessDetail(processDetailEntity);
		} else if (processDetailEntity != null) {
			financeProcessDetailService.createFinanceProcessDetail(processDetailEntity);
		}
		// 发送消息
		FinanceLetterBlockingQueue.putEnterpriseRemindedLetter(getFinanceEnterpriseId(delayEntity.getFinanceId()), "延期还款", "reminded.normal.pickup.delay", pickupEntity.getPickupNumber(), DateUtils.getCurrentLinkedDateTime(),
				delayEntity.getPickupDelayNumber());
		return pickupDelayId.toString();
	}

	@Transactional
	@Override
	public void updatePickupDelayApplication(Long pickupDelayId, String deliveryDate, BigDecimal estimateDelayAmount) {
		PickupDelayApplicationEntity delayEntity = pickupDelayApplicationService.inquirePickupDelayApplication(pickupDelayId);
		delayEntity.setDeliveryDate(DateUtil.parseDateInt(deliveryDate));
		delayEntity.setEstimateDelayAmount(estimateDelayAmount);
		pickupDelayApplicationService.updatePickupDelayApplication(delayEntity);

		// 项目动态
		FinanceProcessDetailEntity processDetailEntity = FinanceProcessCastor.fromPickupDelayApplication(delayEntity, null, null);
		if (processDetailEntity != null && LongUtils.isPrimaryKey(processDetailEntity.getProcessDetailId())) {
			financeProcessDetailService.renovateFinanceProcessDetail(processDetailEntity);
		} else if (processDetailEntity != null) {
			financeProcessDetailService.createFinanceProcessDetail(processDetailEntity);
		}
	}

	@Transactional
	@Override
	public void cancelPickupDelayApplication(Long pickupDelayId) {
		PickupDelayApplicationEntity delayEntity = pickupDelayApplicationService.inquirePickupDelayApplication(pickupDelayId);
		delayEntity.setApplicationState(ApplicationSimpleStateEnum.CANCEL);
		pickupDelayApplicationService.updatePickupDelayApplication(delayEntity);
		// 项目动态
		FinanceProcessDetailEntity processDetailEntity = FinanceProcessCastor.fromPickupDelayApplication(delayEntity, null, true);
		if (processDetailEntity != null && LongUtils.isPrimaryKey(processDetailEntity.getProcessDetailId())) {
			financeProcessDetailService.renovateFinanceProcessDetail(processDetailEntity);
		} else if (processDetailEntity != null) {
			financeProcessDetailService.createFinanceProcessDetail(processDetailEntity);
		}
	}

	@Transactional
	@Override
	public void consentPickupDelayApplication(Long pickupDelayId, BigDecimal auditAmount, String auditRemark) {
		PickupDelayApplicationEntity delayEntity = pickupDelayApplicationService.inquirePickupDelayApplication(pickupDelayId);
		delayEntity.setApplicationState(ApplicationSimpleStateEnum.AGREE);
		delayEntity.setAuditAmount(auditAmount);
		delayEntity.setAuditDateTime(DateUtils.now());
		delayEntity.setAuditor(FinanceSessionContext.getAccountFullName());
		delayEntity.setAuditorId(FinanceSessionContext.getAccountId());
		delayEntity.setAuditRemark(auditRemark);
		delayEntity.setPickupDelayCreateDateTime(DateUtil.now());
		pickupDelayApplicationService.updatePickupDelayApplication(delayEntity);

		PickupApplicationEntity pickupEntity = pickupApplicationService.inquirePickupApplication(delayEntity.getPickupId());
		pickupEntity.setDelayAmount(pickupEntity.getDelayAmount().add(delayEntity.getAuditAmount()));
		pickupEntity.setPickupAmount(pickupEntity.getPickupAmount().add(pickupEntity.getDelayAmount()));
		pickupApplicationService.renovatePickupApplication(pickupEntity);

		// 项目动态
		FinanceProcessDetailEntity processDetailEntity = FinanceProcessCastor.fromPickupDelayApplication(delayEntity, true, null);
		if (processDetailEntity != null && LongUtils.isPrimaryKey(processDetailEntity.getProcessDetailId())) {
			financeProcessDetailService.renovateFinanceProcessDetail(processDetailEntity);
		} else if (processDetailEntity != null) {
			financeProcessDetailService.createFinanceProcessDetail(processDetailEntity);
		}
	}

	@Transactional
	@Override
	public void opposePickupDelayApplication(Long pickupDelayId, Integer disagreeReson, String auditRemark) {
		PickupDelayApplicationEntity persist = pickupDelayApplicationService.inquirePickupDelayApplication(pickupDelayId);
		persist.setDisagreeReson(disagreeReson);
		persist.setApplicationState(ApplicationSimpleStateEnum.DISAGREE);
		persist.setAuditDateTime(DateUtils.now());
		persist.setAuditor(FinanceSessionContext.getAccountFullName());
		persist.setAuditorId(FinanceSessionContext.getAccountId());
		persist.setAuditRemark(auditRemark);
		pickupDelayApplicationService.updatePickupDelayApplication(persist);

		// 项目动态
		FinanceProcessDetailEntity processDetailEntity = FinanceProcessCastor.fromPickupDelayApplication(persist, false, null);
		if (processDetailEntity != null && LongUtils.isPrimaryKey(processDetailEntity.getProcessDetailId())) {
			financeProcessDetailService.renovateFinanceProcessDetail(processDetailEntity);
		} else if (processDetailEntity != null) {
			financeProcessDetailService.createFinanceProcessDetail(processDetailEntity);
		}
	}

	@Override
	public PickupDelayApplicationDetail inquirePickupDelayApplicationDetail(Long pickupDelayId) {
		PickupDelayApplicationEntity entity = pickupDelayApplicationService.inquirePickupDelayApplication(pickupDelayId);
		return BulkstockPledgeCastor.toPickupDelayApplicationDetail(entity);
	}

	@Override
	public PageList<PickupDelayApplicationLineInfo> inquirePickupDelayApplicationPageList(Long[] pickupDelayIds, Long enterpriseId, Long financeId, String financeNumber, String dateBegin, String dateEnd, Integer applicationState,
			PageCriteria page) {
		if (FinanceSessionContext.isEnterprise()) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		ApplicationSimpleStateEnum _enum = null;
		if (applicationState != null) {
			_enum = ApplicationSimpleStateEnum.valueOf(applicationState);
		}
		Date beginDate = null;
		Date endDate = null;
		if (StringUtil.isNotBlank(dateBegin)) {
			beginDate = DateUtil.from(dateBegin);
		}
		if (StringUtil.isNotBlank(dateBegin)) {
			endDate = DateUtil.from(dateEnd);
		}

		PageList<PickupDelayApplicationEntity> pageList = pickupDelayApplicationService.inquirePickupDelayApplicationPageList(pickupDelayIds, enterpriseId, financeId, financeNumber, _enum, beginDate, endDate, page);
		PageList<PickupDelayApplicationLineInfo> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (PickupDelayApplicationEntity entity : pageList) {
			resultList.add(BulkstockPledgeCastor.toPickupDelayApplicationLineInfo(entity));
		}
		return resultList;
	}

	@Override
	public void initInventory() {
		FinanceApplicationActionApiImpl faaai = new FinanceApplicationActionApiImpl();
		List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList(1L);
		for (ContainerInventoryEntity cie : cies) {
			logger.info("换箱同步===");
			HandleSuitcaseResult result = new HandleSuitcaseResult();
			result = faaai.goldLocked(cie.getInventoryId());
			FinanceContainerLogEntity fcle = new FinanceContainerLogEntity();
			fcle.setInventoryId(cie.getInventoryId());
			fcle.setOperator("系统自动加锁");
			if (result != null) {
				fcle.setRemark("加锁 " + result.getMessage());
			} else {
				fcle.setRemark("加锁失败");
			}
			financeContainerLogService.createFinanceContainerLog(fcle);
		}
	}
}
